Dev.to AI 🤖 Ai 👁 0 📖 7 min read

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 explor

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

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)

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

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

Configure the API key through the environment:

export OPENAI_API_KEY="your-api-key"

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())

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

Step 2 — Tool selection

The model selects the relevant operation:

{
  "name": "get_ticket_status",
  "arguments": {
    "ticket_id": 1042
  }
}

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"
}

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.

📰 Read the original article on Dev.to AI

Originally published by Dev.to AI. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.