DEV Community

Cover image for Day 30/90 — Connecting AI Agents to MCP Tools: From Tool Discovery to Real Execution
Rimsha Kanwal
Rimsha Kanwal

Posted on

Day 30/90 — Connecting AI Agents to MCP Tools: From Tool Discovery to Real Execution

An AI agent can reason about a user's request, but reasoning alone cannot retrieve a live database record or check the current status of a support ticket.

For that, the agent needs tools.

Yesterday, on Day 29, I explored building a read-only MCP server with controlled access to backend services.

Today, the challenge is different:

How can we connect an AI assistant to that MCP server and enable it to discover, select, and execute tools automatically?

To explore this, I looked at research on language model tool use, the official MCP specification, and practical agent integration patterns.

1. What Research Tells Us About Tool Use

Two research papers provide useful foundations.

ReAct — Yao et al. (ICLR 2023)

ReAct explores combining reasoning with external actions and observations.

Instead of producing an answer entirely from model knowledge, an agent can interact with an external system, observe the result, and use that information to continue its task.

The underlying pattern is:

User Question
     ↓
Reasoning / Tool Selection
     ↓
External Action
     ↓
Observation
     ↓
Final Response
Enter fullscreen mode Exit fullscreen mode

Toolformer — Schick et al. (NeurIPS 2023)

Toolformer studies how language models can learn to use external APIs.

It focuses on important decisions:

  • Whether an API call is needed.
  • Which API to invoke.
  • What arguments to provide.
  • How to incorporate the returned information.

These papers establish the motivation for tool-using agents.

However, neither paper defines MCP itself. MCP provides a standardized interface through which an application can discover and invoke externally provided capabilities.

2. The Day 30 Engineering Challenge

Consider a document support assistant with access to three tools:

search_documents(query)
get_document(document_id)
get_ticket_status(ticket_id)
Enter fullscreen mode Exit fullscreen mode

These tools are exposed by the read-only MCP server from Day 29.

Suppose the user asks:

"What is the current status of ticket 1042?"

The assistant must:

  1. Discover the available MCP tools.
  2. Identify get_ticket_status as relevant.
  3. Generate the correct ticket_id argument.
  4. Execute the tool through the MCP client.
  5. Read the returned data.
  6. Generate an answer supported by that data.

This is the end-to-end behavior the challenge requires.

3. Understanding the Architecture

                  USER
                   |
                   v
              AI ASSISTANT
                   |
          Tool Selection (LLM)
                   |
                   v
             MCP CLIENT
                   |
          MCP Protocol Layer
                   |
                   v
              MCP SERVER
                   |
        Validation & Authorization
                   |
                   v
          Backend Services
                   |
                   v
              Tool Result
                   |
                   v
              AI ASSISTANT
                   |
                   v
             User Response
Enter fullscreen mode Exit fullscreen mode

An important detail: the LLM does not directly access the database.

The MCP client handles communication, while the backend remains responsible for validating requests and enforcing permissions.

This separation helps prevent model-generated tool arguments from becoming unrestricted backend operations.

4. Connecting an AI Assistant to the MCP Server

For this implementation, I chose Python, the official MCP SDK, and the OpenAI Agents SDK.

The example assumes that the read-only MCP server from Day 29 is already running at:

http://localhost:8000/mcp

Install the dependencies:

pip install "mcp>=2,<3" openai-agents
Enter fullscreen mode Exit fullscreen mode

Configure the API key through the environment:

export OPENAI_API_KEY="your-api-key"
Enter fullscreen mode Exit fullscreen mode

On Windows PowerShell, use $env:OPENAI_API_KEY instead.

Now create assistant.py:

import asyncio

from agents import Agent, Runner
from agents.mcp import MCPServerStreamableHttp


async def main():

    async with MCPServerStreamableHttp(
        name="Document Support MCP",
        params={
            "url": "http://localhost:8000/mcp",
            "timeout": 10,
        },
        cache_tools_list=True,
    ) as server:

        # Discover the tools exposed by the server
        tools = await server.list_tools()

        print("Available MCP tools:")

        for tool in tools:
            print(f"- {tool.name}")

        # Connect the discovered tools to the agent
        agent = Agent(
            name="Document Support Assistant",
            instructions=(
                "Use the available MCP tools to retrieve "
                "documents and ticket information. "
                "Never invent ticket statuses or document "
                "contents. If a tool fails or information "
                "is unavailable, explain the limitation."
            ),
            mcp_servers=[server],
        )

        # Run an end-to-end user request
        result = await Runner.run(
            agent,
            "What is the status of ticket 1042?"
        )

        print("\nAssistant response:")
        print(result.final_output)


if __name__ == "__main__":
    asyncio.run(main())
Enter fullscreen mode Exit fullscreen mode

This example uses the local Streamable HTTP integration documented by the OpenAI Agents SDK.

The SDK connects the agent to the MCP server and makes its discovered tools available to the model.

For this read-only demonstration, tool selection is model-driven, but the backend still controls what each tool can do.

5. What Happens During Execution?

Consider the following illustrative sequence.

Step 1 — Tool discovery

The assistant receives the available tool definitions.

Available MCP tools:
- search_documents
- get_document
- get_ticket_status
Enter fullscreen mode Exit fullscreen mode

Step 2 — Tool selection

The model selects the relevant operation:

{
  "name": "get_ticket_status",
  "arguments": {
    "ticket_id": 1042
  }
}
Enter fullscreen mode Exit fullscreen mode

Step 3 — Tool execution

The MCP client sends the invocation to the server.

The server validates the request, checks access permissions, and retrieves the requested information.

Step 4 — Example backend response

{
  "ticket_id": 1042,
  "status": "in_progress",
  "priority": "high"
}
Enter fullscreen mode Exit fullscreen mode

Step 5 — Expected assistant response

"Ticket 1042 is currently in progress and has high priority."

The status and priority values here are synthetic examples. A real execution must use the actual backend response.

The critical improvement over an unsupported answer is that the assistant can ground its response in information returned by an external service.

6. Why Tool Discovery Alone Is Not Enough

A client successfully connecting to an MCP server does not prove that the agent can use its tools correctly.

A complete evaluation must inspect the entire execution chain.

For example, the assistant might discover three tools but choose the wrong one.

It might choose the correct tool but generate invalid arguments.

Or the MCP server might return an error that the assistant incorrectly interprets as a successful result.

This means tool integration quality has multiple dimensions:

Component What to verify
Discovery Correct tools are exposed
Selection Appropriate tool is chosen
Arguments Inputs match the expected schema
Authorization Requests obey access restrictions
Execution Tool returns the expected result
Final response Answer agrees with tool output

These checks provide better evidence than simply showing a plausible final answer.

7. Testing the Integration

I would evaluate the implementation using a small controlled dataset of synthetic tickets and documents.

The initial test cases would include:

Test 1: Valid ticket

Ask for a ticket that exists and is authorized.

Expected: The correct status is retrieved and reported.

Test 2: Missing ticket

Ask for a nonexistent ticket.

Expected: The assistant reports that the ticket was not found rather than inventing its status.

Test 3: Unauthorized ticket

Request a ticket outside the caller's permitted scope.

Expected: Backend authorization denies access, and the assistant does not reveal the protected information.

Test 4: Invalid arguments

Submit a request containing an invalid ticket identifier.

Expected: Validation rejects the request safely.

Test 5: Unavailable MCP server

Temporarily disconnect the backend.

Expected: The application returns a controlled error instead of presenting fabricated information.

For a stronger assessment, collect execution traces and compare the selected tools, arguments, and final answers against expected outcomes.

Useful metrics include tool-selection accuracy, execution success rate, grounded-answer accuracy, and end-to-end latency.

These tests describe the validation plan. They are not claims that the example has already passed all five scenarios.

8. Research Insight: Tool Use Is Not the Same as Reliability

The ReAct and Toolformer papers help explain why external tools can make language models more capable.

But building a dependable production system requires additional engineering.

MCP standardizes how tools are exposed and invoked. It does not guarantee that an agent will select the correct tool, generate valid arguments, or interpret a response accurately.

There are also security considerations.

A read-only MCP server can still expose sensitive information if authorization is missing.

Tool output can also contain untrusted text, which should be treated as data rather than as instructions to the agent.

For that reason, a production integration needs least-privilege access, input validation, output checks, timeouts, structured error handling, and execution tracing.

The model makes decisions about what to request. The application remains responsible for deciding what is permitted.

9. What I Would Measure Before Calling This Complete

The Day 30 challenge is not fully demonstrated by writing the integration code alone.

The final evidence should show a real end-to-end execution in which:

  • The MCP client successfully discovers the tools.
  • The assistant chooses the expected tool.
  • The correct arguments reach the server.
  • The server returns real test data.
  • The assistant's final answer accurately reflects that data.

The same workflow should then be tested under failure and authorization scenarios.

This distinction matters because a successful demo and a reliable integration are not necessarily the same thing.

Final Thoughts

Day 29 focused on building a controlled MCP server.

Day 30 brings that server into an AI assistant's execution workflow.

Research such as ReAct and Toolformer helps explain the value of combining language models with external capabilities.

MCP provides a standardized communication layer to put that idea into practice.

But the core engineering lesson is broader:

Connecting an LLM to tools creates capability. Validating the complete tool execution lifecycle creates reliability.

An AI agent becomes more useful when it can interact with real systems, but it becomes more** trustworthy **when those interactions are observable, authorized, and verifiable.

Top comments (7)

Collapse
 
paul_irolla_6b5ae261d0224 profile image
Paul Irolla •

@rimsha_kanwal agreed on the split. Definitions are paid once, at the start. Each tool result is paid again on every later turn it stays in context, so a session with large outputs grows faster than one with many tools.

Collapse
 
rimsha_kanwal profile image
Rimsha Kanwal •

That's a good point! I think keeping tool responses small and relevant becomes even more important as the conversation grows. Thanks for sharing your perspective!

Collapse
 
rimsha_kanwal profile image
Rimsha Kanwal •

References

Yao, S., et al. (2023). ReAct: Synergizing Reasoning and Acting in Language Models. ICLR.
arxiv.org/abs/2210.03629

Model Context Protocol. (2026). Tools — MCP Specification, 2026-07-28.
github.com/modelcontextprotocol/mo...

OpenAI. Agents SDK — MCP Integration Documentation.
openai.github.io/openai-agents-pyt...

Model Context Protocol. Official Python SDK — Client Documentation.
py.sdk.modelcontextprotocol.io/cli...

Collapse
 
paul_irolla_6b5ae261d0224 profile image
Paul Irolla •

Discovery and execution cost different things: the definitions you load, and the results you get back. Which of the two grows your context more?

Collapse
 
rimsha_kanwal profile image
Rimsha Kanwal •

Good! I think tool definitions take up more context at the start, but as the agent keeps making calls, the results can add up pretty quickly, especially with large responses. So it really depends on how many tools you're using and how much data they're returning.

Collapse
 
paul_irolla_6b5ae261d0224 profile image
Paul Irolla •

@rimsha_kanwal Agreed, and the effect compounds. A tool result that is large on turn two is paid again on every turn after it, so trimming it at the source beats trimming it later.

Collapse
 
rimsha_kanwal profile image
Rimsha Kanwal •

Exactly! That's why minimizing tool outputs at the source is so important. Small optimizations early can make a big difference in long-running agent workflows.