Skip to content
~/series/agentic-workflows/mcp-protocol
EST: 30mSECTIONS: 11SKILLS: 6

Lesson 3 · Agentic workflows

30 min readAdvanced

Model Context Protocol (MCP)

A standard protocol for connecting agents to tool ecosystems. Servers, clients, capabilities.

What contains a community MCP server that exposes run_shell

Step 1 of 4

Review and pin

Read the source of any community server before connecting, and pin the server and SDK versions so its capabilities cannot change under you.

Treat an external server as untrusted code that runs with your agent's privileges.

What is MCP?

The Model Context Protocol (MCP) is an open standard for connecting AI applications to external tools, data sources and capabilities. An MCP server exposes tools (functions), resources (data), and prompts (templates). An MCP client (your agent) connects to servers and uses what they expose.

In production, MCP has evolved from simple local scripts into an enterprise integration standard with three core pillars:

1. Remote HTTP+SSE transports: while local stdio works for desktop developer agents, production cloud agents connect to remote MCP servers over HTTP with Server-Sent Events (SSE). Remote MCP decouples agent execution from tool containers, enabling independent scaling and isolated failure domains.

2. Dynamic tool search and routing: passing 100+ tool schemas into an LLM's prompt consumes tens of thousands of tokens, increases latency, and degrades tool selection accuracy. Production agents maintain a semantic tool registry, using vector search or intent routing to inject only the top 3-5 relevant tool schemas for the active turn.

3. OAuth and least-privilege security: remote MCP servers enforce OAuth 2.0 authentication with granular scopes, least-privilege database roles, and input/output sanitization to defend against indirect prompt injection.

Why MCP matters

Before MCP, every agent framework had its own tool format. Switching frameworks meant rewriting tools. MCP standardises the interface, so a Postgres or GitHub MCP server works with any MCP client.

In enterprise systems, MCP solves the tool governance bottleneck: security teams can audit, authenticate (via OAuth), and sandbox a single MCP server that powers dozens of internal agents. Combined with dynamic tool routing, agents can access massive corporate tool catalogs without prompt bloat or context degradation.

MCP architecture

Enterprise Remote MCP architecture:

Agent client runtime → OAuth 2.0 bearer token authentication → Remote MCP Gateway (HTTP POST + SSE streaming) → Dynamic tool routing layer (embeds query → retrieves top-3 relevant schemas from 100+ tool catalog) → Injects filtered tools into LLM context → Tool call executed in sandboxed container → Validated response returned to agent.

An MCP server and client

mcp_example.py
# Written against the MCP Python SDK 1.x (pip install "mcp>=1.2,<2"), checked
# against its README on 28 October 2026. SDK 2.x renames FastMCP to MCPServer
# (from mcp.server.mcpserver import MCPServer) and uses snake_case fields
# such as tool.input_schema; see the SDK's migration guide.

# ---------- postgres_server.py: exposes a read-only query tool ----------
# Read-only is enforced by the database, not by inspecting the SQL. Create a
# role that can only read, once, as an admin:
#   CREATE ROLE mcp_readonly LOGIN PASSWORD '...';
#   GRANT CONNECT ON DATABASE products TO mcp_readonly;
#   GRANT USAGE ON SCHEMA public TO mcp_readonly;
#   GRANT SELECT ON ALL TABLES IN SCHEMA public TO mcp_readonly;
#   ALTER ROLE mcp_readonly SET default_transaction_read_only = on;
#   ALTER ROLE mcp_readonly SET statement_timeout = '5s';
import json
import os

import psycopg
from psycopg.rows import dict_row
from mcp.server.fastmcp import FastMCP

mcp = FastMCP("postgres-tools")

# Connects as the read-only role: INSERT, UPDATE, DELETE and DDL fail with a
# permission error whatever SQL the model sends.
db = psycopg.connect(os.environ["READONLY_DATABASE_URL"], row_factory=dict_row, autocommit=True)

@mcp.tool()
def query_postgres(sql: str) -> str:
    """Run a read-only SQL query against the products database. Use for product and inventory questions."""
    try:
        rows = db.execute(sql).fetchmany(200)  # cap the result size
    except psycopg.Error as e:
        return json.dumps({"error": str(e)})
    return json.dumps(rows, default=str)

if __name__ == "__main__":
    mcp.run()  # stdio transport by default

# ---------- agent.py: an MCP client that lets the model use the tools ----------
import asyncio
import json

from mcp import ClientSession, StdioServerParameters, types
from mcp.client.stdio import stdio_client
from openai import OpenAI

llm = OpenAI()
# Model names change often; check your provider's model list (as of 28 October 2026). Replace <...-model> with a model id from that list.

server_params = StdioServerParameters(
    command="python",
    args=["postgres_server.py"],
    env={"READONLY_DATABASE_URL": "postgresql://mcp_readonly@localhost/products"},
)

def to_openai_tool(tool: types.Tool) -> dict:
    """MCP tool definition -> the OpenAI tools format."""
    return {
        "type": "function",
        "function": {"name": tool.name, "description": tool.description or "", "parameters": tool.inputSchema},
    }

def result_text(result: types.CallToolResult) -> str:
    return "\n".join(c.text for c in result.content if isinstance(c, types.TextContent))

async def run_agent_with_mcp(task: str, max_steps: int = 5) -> str:
    async with stdio_client(server_params) as (read, write):
        async with ClientSession(read, write) as session:
            await session.initialize()
            listed = await session.list_tools()  # discover what the server exposes
            tools = [to_openai_tool(t) for t in listed.tools]

            messages = [{"role": "user", "content": task}]
            for _ in range(max_steps):
                response = llm.chat.completions.create(model="<small-model>", messages=messages, tools=tools)
                msg = response.choices[0].message
                if not msg.tool_calls:
                    return msg.content
                messages.append(msg)
                for tc in msg.tool_calls:
                    result = await session.call_tool(tc.function.name, arguments=json.loads(tc.function.arguments))
                    messages.append({"role": "tool", "tool_call_id": tc.id, "content": result_text(result)})
            return "Stopped after max_steps without a final answer."

if __name__ == "__main__":
    print(asyncio.run(run_agent_with_mcp("Which products are low on stock?")))

Experiment: tool ecosystem

See how MCP enables a reusable tool ecosystem.

Choose an integration approach. See the trade-offs.

What to observe

MCP decouples tools from agents. Write a server once; any MCP-compatible agent uses it. For multi-agent systems, this eliminates tool duplication and drift. For single agents, the overhead may not be worth it yet — but the ecosystem is growing.

Production MCP

Production MCP: pin server and SDK versions, enforce read-only in the system behind the tool (a read-only database role, not a check on the SQL text), audit every tool call, sandbox server processes (don't trust arbitrary servers), and version the capabilities you expose. For external servers (community), review the source before connecting — they run with your agent's privileges.

Challenge

You connect a community MCP server that exposes a 'run_shell' tool. Your agent uses it. What's the security risk and how do you mitigate it?

Production checklist

Production checklist

0 of 11 checked

Knowledge check

What's the primary benefit of MCP over per-agent custom tools?

Complete

You can now build, secure, and route MCP servers for reusable tool ecosystems. This completes the Agentic workflows series.

Mark this chapter as complete

Track your progress and unlock the next chapter.

Email updates

Get the next chapter and new guides by email.

One email per substantial release. Unsubscribe in one click.

We will email you a confirmation link first, then send an occasional email when a substantial guide is published. Unsubscribe in one click. Stored with our email provider (Resend), never sold or shared. See the privacy policy.

Continue learning