PromptisePromptise
PlatformSoonEnterprise
DocsGitHub
Talk to usGet started
Promptise - AI Framework LogoPromptise

The full-stack framework for agentic systems. Build with the framework. Run it on the platform. Launch it with our engineers.

pip install promptise

[01] Product

  • Framework
  • Platform (coming soon)
  • Enterprise
  • How it works
  • Contact

[02] Framework

  • The Agent
  • The Interface
  • The Harness

[03] Resources

  • Documentation
  • GitHub
  • Why Promptise
  • Use cases
  • Roadmap
  • Guides
  • Learning Paths
  • Questions

[04] Company

  • About
  • Terms of Service
  • Privacy Policy
  • Cookie Policy
  • Subprocessors

© 2026 Promptise by Manser Ventures. All rights reserved.

hello@promptise.com
← Learning paths> Agentic Engineering with Promptise Foundry
Lesson 19 / 100
19%

How to Connect MCP Servers to Your AI Agent in Python

Give your AI agent real tools with the Model Context Protocol. Connect local and remote MCP servers to a Python agent, step by step, with code you can run.

Beginner12 minModel Context Protocol (MCP)Tool Calling
All 100 lessons↓
  1. ✓What Is an AI Agent? Definition, How It Works, Examples
  2. ✓How to Build an AI Agent in Python (2026 Guide)
  3. ✓Build a Personal AI Agent: Memory, Reminders, Chat
  4. ✓What Is an Agent Harness? Parts and How to Build One
  5. ✓System Prompt Best Practices for AI Agents in Python
  6. ✓Best LLM for AI Agents (2026): Picks, Prices, How to Test
  7. ✓AI Agent YAML: Define and Run an Agent From a Config File
  8. ✓Streaming LLM Responses with FastAPI: Tokens and Tool Calls
  9. ✓Best Local LLM for AI Agents: Ollama Models by GPU (2026)
  10. ✓Claude AI Agent with MCP: Use Anthropic Models in Promptise
  11. ✓Gemini AI Agent with MCP: Use Google Models in Promptise
  12. ✓Azure OpenAI Agent with MCP: Use Deployments in Promptise
  13. ✓OpenRouter AI Agent with MCP: Many Models in Promptise
  14. ✓Ollama AI Agent with MCP: Run Local Models in Promptise
  15. ✓LLM Semantic Cache and Model Fallback in Python
  16. ✓What Is MCP (Model Context Protocol)? A Developer's Guide
  17. ✓What Is Tool Calling? LLM Function Calling Explained
  18. ✓MCP Tools vs Resources vs Prompts (With Python Examples)
  19. 19How to Connect MCP Servers to Your AI Agent in Python
  20. 20Build a Production MCP Server in Python (Step by Step)
  21. 21MCP Transports: stdio vs Streamable HTTP vs SSE (Python)
  22. 22MCP 2026-07-28 Migration: Make Your MCP Server Stateless
  23. 23OpenAPI to MCP: Turn Any REST API into an MCP Server
  24. 24MCP Authentication in Python: API Keys, JWT and OAuth
  25. 25Build an Authenticated MCP Server for Your AI Agent (Python)
  26. 26MCP Security Best Practices: A Checklist for MCP Servers
  27. 27Testing MCP Servers in Python: pytest Without a Live Server
  28. 28Too Many MCP Tools? How to Fix LLM Tool Selection in Python
  29. 29Idempotent Tool Calls: Make AI Agent Retries Safe
  30. 30AI Agent Tool Failures: Stop Unsafe Workarounds
  31. 31MCP Server Caching, Timeouts and Circuit Breakers in Python
  32. 32MCP Middleware for Servers: Auth, Logging, Rate Limits
  33. 33MCP vs CLI for AI Agents: Tokens, Security, When to Use Each
  34. 34LangChain vs MCP: Differences and How They Work Together
  35. 35FastMCP Alternatives for Production MCP Servers (2026)
  36. 36AI Agent Audit Logging: Tamper-Evident Logs in Python
  37. 37AI Agent Human in the Loop: Approve Tool Calls in Python
  38. 38AI Agent Prompt Injection: How to Defend Against It
  39. 39Hidden Text Prompt Injection: Sanitize Pages for AI Agents
  40. 40Build a Multi-Agent System in Python (and When Not To)
  41. 41Context Engineering for AI Agents: Context Window Management
  42. 42Context Compaction for AI Agents: Trim vs Summarize
  43. 43How to Deploy an AI Agent with Docker (2026 Guide)
  44. 44LLM Tool Rate Limiting: Per-Client Limits for MCP Servers
  45. 45MCP Long-Running Tasks: Background Jobs in Python
  46. 46MCP Server Monitoring: Prometheus, OpenTelemetry and Logs
  47. 47Best AI Agent Frameworks (2026): Python Options Compared
  48. 48Self-Improving AI Agent: Learn From Tool Failures in Python
  49. 49AI Agent Identity: Authenticate Agents to MCP Servers
  50. 50Code-Action Agents in Python: One Program vs 37 Tool Calls
  51. 51Multi-Tenant AI Agents: Keep Each Customer's Data Apart
  52. 52What Is Agentic RAG? How It Differs from Classic RAG
  53. 53AI Agent Memory in Python: Short-Term and Long-Term
  54. 54Per-User Agent Memory Isolation: Stop Leaks Between Users
  55. 55Agentic RAG in Python: Give Your AI Agent a Search Tool
  56. 56AI Agent Reasoning Patterns in Python: From ReAct to Debate
  57. 57Plan-and-Execute Agents in Python: Beyond the ReAct Loop
  58. 58Self-Modifying AI Agent in Python: Open Mode & Limits
  59. 59CrewAI Alternatives: 7 Options and How to Migrate (2026)
  60. 60Migrate from AutoGen: Agent Framework, AG2 and More
  61. 61What Is an LLM Guardrail? Types, Examples and Limits
  62. 62Best LLM Guardrails Tools (2026): 9 Platforms Compared
  63. 63AI Agent Guardrails in Python: Block Injection, Redact PII
  64. 64NeMo Guardrails vs Guardrails AI: Which to Choose (2026)
  65. 65AI-Based PII Detection and Redaction Tools for LLM Apps
  66. 66Stop Secrets Leaking Into LLM Logs and Traces
  67. 67AI Agent Code Execution Sandbox: Run LLM Code Safely
  68. 68AI Agent Network Egress: Limit Where Agents Can Connect
  69. 69AutoGen Docker Task Isolation: Secure the Code Executor
  70. 70SPIFFE for AI Agents: Workload Identity Without API Keys
  71. 71On-Behalf-Of Auth for AI Agents: Act as Each User
  72. 72AI Agent Production Checklist: What to Check Before Launch
  73. 73Approval Fatigue: Auto-Approve Safe AI Agent Actions
  74. 74What Is Human in the Loop AI? Approvals for AI Agents
  75. 75AI Agent Notifications: Webhook and Slack Alerts in Python
  76. 76AI Agent Observability: Trace Tool Calls, Tokens and Cost
  77. 77Best AI Agent Observability Tools (2026), Compared
  78. 78AI Agent Stuck in a Loop? How to Detect and Stop It
  79. 79How to Run, Debug and Deploy an AI Agent in Python
  80. 80AI Agent Cost Tracking: Tokens and Cost per Run and User
  81. 81How to Evaluate AI Agents: Evals, LLM Judges and pass^k
  82. 82AI Agent Cost Control: Budgets That Stop Runaway Spend
  83. 83How to Test LLM Prompts and AI Agents in Python
  84. 84AI Agent Evals in CI: Run Them on Every Pull Request
  85. 85What Is an Agentic Runtime? AI Agent Runtimes Explained
  86. 86Autonomous AI Agent Runtime: Budgets, Crash Recovery, API
  87. 87Event-Driven AI Agents: Webhook, Cron and File Triggers
  88. 88AI Agent Cron Jobs: Run an Agent on a Schedule
  89. 89AI Agent Webhook Trigger: Run an Agent on HTTP Events
  90. 90AI Agent File Watcher: Process New Files Automatically
  91. 91Custom AI Agent Triggers: Wake an Agent From Any Source
  92. 92AI Agent Event Filters: Skip Runs Before the LLM
  93. 93AI Agent Retries and a Dead Letter Queue for Failed Runs
  94. 94Run Multiple AI Agents: One Runtime, Many Processes
  95. 95AI Agent Manifest: Declare a Long-Running Agent in YAML
  96. 96AI Agent CLI: Start, Stop and Inspect Running Agents
  97. 97AI Agent Monitoring Dashboard in the Terminal
  98. 98Multi-Agent Event Bus: Chain Agents With Events
  99. 99Distributed AI Agents: Run Agents Across Many Machines
  100. 100Pause and Resume an AI Agent: Lifecycle States Explained

Lessons in this path

  1. ✓What Is an AI Agent? Definition, How It Works, Examples
  2. ✓How to Build an AI Agent in Python (2026 Guide)
  3. ✓Build a Personal AI Agent: Memory, Reminders, Chat
  4. ✓What Is an Agent Harness? Parts and How to Build One
  5. ✓System Prompt Best Practices for AI Agents in Python
  6. ✓Best LLM for AI Agents (2026): Picks, Prices, How to Test
  7. ✓AI Agent YAML: Define and Run an Agent From a Config File
  8. ✓Streaming LLM Responses with FastAPI: Tokens and Tool Calls
  9. ✓Best Local LLM for AI Agents: Ollama Models by GPU (2026)
  10. ✓Claude AI Agent with MCP: Use Anthropic Models in Promptise
  11. ✓Gemini AI Agent with MCP: Use Google Models in Promptise
  12. ✓Azure OpenAI Agent with MCP: Use Deployments in Promptise
  13. ✓OpenRouter AI Agent with MCP: Many Models in Promptise
  14. ✓Ollama AI Agent with MCP: Run Local Models in Promptise
  15. ✓LLM Semantic Cache and Model Fallback in Python
  16. ✓What Is MCP (Model Context Protocol)? A Developer's Guide
  17. ✓What Is Tool Calling? LLM Function Calling Explained
  18. ✓MCP Tools vs Resources vs Prompts (With Python Examples)
  19. 19How to Connect MCP Servers to Your AI Agent in Python
  20. 20Build a Production MCP Server in Python (Step by Step)
  21. 21MCP Transports: stdio vs Streamable HTTP vs SSE (Python)
  22. 22MCP 2026-07-28 Migration: Make Your MCP Server Stateless
  23. 23OpenAPI to MCP: Turn Any REST API into an MCP Server
  24. 24MCP Authentication in Python: API Keys, JWT and OAuth
  25. 25Build an Authenticated MCP Server for Your AI Agent (Python)
  26. 26MCP Security Best Practices: A Checklist for MCP Servers
  27. 27Testing MCP Servers in Python: pytest Without a Live Server
  28. 28Too Many MCP Tools? How to Fix LLM Tool Selection in Python
  29. 29Idempotent Tool Calls: Make AI Agent Retries Safe
  30. 30AI Agent Tool Failures: Stop Unsafe Workarounds
  31. 31MCP Server Caching, Timeouts and Circuit Breakers in Python
  32. 32MCP Middleware for Servers: Auth, Logging, Rate Limits
  33. 33MCP vs CLI for AI Agents: Tokens, Security, When to Use Each
  34. 34LangChain vs MCP: Differences and How They Work Together
  35. 35FastMCP Alternatives for Production MCP Servers (2026)
  36. 36AI Agent Audit Logging: Tamper-Evident Logs in Python
  37. 37AI Agent Human in the Loop: Approve Tool Calls in Python
  38. 38AI Agent Prompt Injection: How to Defend Against It
  39. 39Hidden Text Prompt Injection: Sanitize Pages for AI Agents
  40. 40Build a Multi-Agent System in Python (and When Not To)
  41. 41Context Engineering for AI Agents: Context Window Management
  42. 42Context Compaction for AI Agents: Trim vs Summarize
  43. 43How to Deploy an AI Agent with Docker (2026 Guide)
  44. 44LLM Tool Rate Limiting: Per-Client Limits for MCP Servers
  45. 45MCP Long-Running Tasks: Background Jobs in Python
  46. 46MCP Server Monitoring: Prometheus, OpenTelemetry and Logs
  47. 47Best AI Agent Frameworks (2026): Python Options Compared
  48. 48Self-Improving AI Agent: Learn From Tool Failures in Python
  49. 49AI Agent Identity: Authenticate Agents to MCP Servers
  50. 50Code-Action Agents in Python: One Program vs 37 Tool Calls
  51. 51Multi-Tenant AI Agents: Keep Each Customer's Data Apart
  52. 52What Is Agentic RAG? How It Differs from Classic RAG
  53. 53AI Agent Memory in Python: Short-Term and Long-Term
  54. 54Per-User Agent Memory Isolation: Stop Leaks Between Users
  55. 55Agentic RAG in Python: Give Your AI Agent a Search Tool
  56. 56AI Agent Reasoning Patterns in Python: From ReAct to Debate
  57. 57Plan-and-Execute Agents in Python: Beyond the ReAct Loop
  58. 58Self-Modifying AI Agent in Python: Open Mode & Limits
  59. 59CrewAI Alternatives: 7 Options and How to Migrate (2026)
  60. 60Migrate from AutoGen: Agent Framework, AG2 and More
  61. 61What Is an LLM Guardrail? Types, Examples and Limits
  62. 62Best LLM Guardrails Tools (2026): 9 Platforms Compared
  63. 63AI Agent Guardrails in Python: Block Injection, Redact PII
  64. 64NeMo Guardrails vs Guardrails AI: Which to Choose (2026)
  65. 65AI-Based PII Detection and Redaction Tools for LLM Apps
  66. 66Stop Secrets Leaking Into LLM Logs and Traces
  67. 67AI Agent Code Execution Sandbox: Run LLM Code Safely
  68. 68AI Agent Network Egress: Limit Where Agents Can Connect
  69. 69AutoGen Docker Task Isolation: Secure the Code Executor
  70. 70SPIFFE for AI Agents: Workload Identity Without API Keys
  71. 71On-Behalf-Of Auth for AI Agents: Act as Each User
  72. 72AI Agent Production Checklist: What to Check Before Launch
  73. 73Approval Fatigue: Auto-Approve Safe AI Agent Actions
  74. 74What Is Human in the Loop AI? Approvals for AI Agents
  75. 75AI Agent Notifications: Webhook and Slack Alerts in Python
  76. 76AI Agent Observability: Trace Tool Calls, Tokens and Cost
  77. 77Best AI Agent Observability Tools (2026), Compared
  78. 78AI Agent Stuck in a Loop? How to Detect and Stop It
  79. 79How to Run, Debug and Deploy an AI Agent in Python
  80. 80AI Agent Cost Tracking: Tokens and Cost per Run and User
  81. 81How to Evaluate AI Agents: Evals, LLM Judges and pass^k
  82. 82AI Agent Cost Control: Budgets That Stop Runaway Spend
  83. 83How to Test LLM Prompts and AI Agents in Python
  84. 84AI Agent Evals in CI: Run Them on Every Pull Request
  85. 85What Is an Agentic Runtime? AI Agent Runtimes Explained
  86. 86Autonomous AI Agent Runtime: Budgets, Crash Recovery, API
  87. 87Event-Driven AI Agents: Webhook, Cron and File Triggers
  88. 88AI Agent Cron Jobs: Run an Agent on a Schedule
  89. 89AI Agent Webhook Trigger: Run an Agent on HTTP Events
  90. 90AI Agent File Watcher: Process New Files Automatically
  91. 91Custom AI Agent Triggers: Wake an Agent From Any Source
  92. 92AI Agent Event Filters: Skip Runs Before the LLM
  93. 93AI Agent Retries and a Dead Letter Queue for Failed Runs
  94. 94Run Multiple AI Agents: One Runtime, Many Processes
  95. 95AI Agent Manifest: Declare a Long-Running Agent in YAML
  96. 96AI Agent CLI: Start, Stop and Inspect Running Agents
  97. 97AI Agent Monitoring Dashboard in the Terminal
  98. 98Multi-Agent Event Bus: Chain Agents With Events
  99. 99Distributed AI Agents: Run Agents Across Many Machines
  100. 100Pause and Resume an AI Agent: Lifecycle States Explained
← Path overview

An AI agent is only as useful as the tools it can reach. The Model Context Protocol (MCP) is the open standard for giving it those tools: a small server offers a set of functions, and your agent connects to it as a client. In this guide you'll build a tiny MCP server, connect it to a Python agent, then add a remote server and an open-source one next to it. Every output below is what a real run printed, with gpt-5-mini as the model.

[01]

How do you connect an MCP server to an AI agent?

You tell the agent where each server lives, and it does the rest. With Promptise Foundry, that's the servers argument of build_agent:

Python
1
2
3
4
5
6
7
8
9
10
from promptise import build_agent
from promptise.config import HTTPServerSpec, StdioServerSpec

agent = await build_agent(
    model="openai:gpt-5-mini",
    servers={
        "orders": StdioServerSpec(command="python", args=["orders_server.py"]),
        "crm": HTTPServerSpec(url="https://mcp.example.com/mcp"),
    },
)

When the agent starts, it connects to every server, asks each one which tools it offers, and hands that list to the model. When the model decides a tool will help, the agent calls it on the right server and passes the result back. You write no glue code per tool. The rest of this guide shows each piece working.


[02]

How MCP fits into your agent

Think of an MCP server as a counter between your agent and your systems. The agent asks; the server decides what's allowed and does the work. The agent never touches your database directly.

Rendering diagram…

That boundary is what makes MCP worth it. You can swap the model, change frameworks, or add a second agent, and the servers stay exactly as they are.

Servers talk to agents in one of two ways:

stdio

HTTP

How it runs

The agent starts the server as a child process

The server runs on its own; the agent connects by URL

Good for

Local tools, development, single-user apps

Shared services, production, anything behind auth

In Promptise

StdioServerSpec

HTTPServerSpec


[03]

What you need

  • Python 3.10 or newer.

  • An API key for a model provider. This guide uses OpenAI. Anthropic, Gemini, Azure, Bedrock, Ollama and others work by changing the model string, as listed in Models & Providers.

  • Promptise Foundry, which installs from PyPI:

>_Terminal
pip install promptise
export OPENAI_API_KEY="sk-..."

[04]

Build and connect your first MCP server

We'll give a support assistant one job: tell customers where their order is.

Step 01

Write a small MCP server

An MCP server is a normal Python file. Each function you decorate with @server.tool() becomes a tool the agent can call. Promptise builds the tool's input schema from your type hints.

Pythonorders_server.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
from promptise.mcp.server import MCPServer

server = MCPServer("orders")

# A stand-in for your real database or API.
ORDERS = {
    "A-1001": {"status": "shipped", "carrier": "DHL", "eta": "2026-10-14"},
    "A-1002": {"status": "processing", "carrier": None, "eta": None},
}


@server.tool()
async def get_order_status(order_id: str) -> dict:
    """Get an order's status, carrier and expected delivery date.

    Args:
        order_id: The order ID, for example "A-1001".
    """
    order = ORDERS.get(order_id.strip().upper())
    if order is None:
        return {"error": f"No order found with ID {order_id}."}
    return {"order_id": order_id.strip().upper(), **order}


if __name__ == "__main__":
    server.run()

Two details matter more than they look:

  • The docstring is written for the model. Its first paragraph becomes the tool's description, and each entry under Args: describes a parameter. That's what the model reads when it decides whether to call the tool and what to pass, so say plainly what the tool does and what each input looks like.

  • A missing order comes back as data, not an exception. The model can read "No order found" and tell the customer something useful.

Step 02

Connect it to your agent

Create a second file next to the first one:

Pythonagent.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import asyncio
import sys

from promptise import build_agent
from promptise.config import StdioServerSpec


async def main():
    agent = await build_agent(
        model="openai:gpt-5-mini",
        servers={
            "orders": StdioServerSpec(command=sys.executable, args=["orders_server.py"]),
        },
        instructions=(
            "You are a friendly support assistant. Use your tools to answer "
            "questions about orders. Only offer help your tools can provide."
        ),
        trace_tools=True,
    )
    try:
        print("Tools:", agent.tool_names)
        result = await agent.ainvoke(
            {"messages": [{"role": "user", "content": "Hi! Where is my order A-1001?"}]}
        )
        print(result["messages"][-1].content)
    finally:
        await agent.shutdown()


asyncio.run(main())

A few things are happening here:

  • StdioServerSpec tells the agent to start orders_server.py itself. Using sys.executable runs the server with the same Python, and the same installed packages, as your agent.

  • trace_tools=True prints every tool call, so you can watch the agent work.

  • agent.shutdown() closes the connection and stops the server process. The try/finally makes sure that happens even if something fails.

Step 03

Run it

>_Terminal
python agent.py
Output
Tools: ['get_order_status']
→ Invoking tool: get_order_status with {'order_id': 'A-1001'}
✔ Tool result from get_order_status: {"order_id": "A-1001", "status": "shipped", "carrier": "DHL", "eta": "2026-10-14"}
Thanks — I found your order A-1001.

- Status: shipped
- Carrier: DHL
- Estimated delivery date: 2026-10-14

Would you like me to track the shipment in real time, update the delivery address, or file an issue with DHL?

Follow the arrows. The agent found one tool on the server. The model chose it, pulled the order ID out of the question, and wrote its answer from the result. Your agent code doesn't mention orders anywhere: it learned about the tool from the server. The wording of the final reply will be a little different each time you run it, because the model writes it fresh. Look at the last line too: the model offered to track the shipment, change the delivery address and file an issue with DHL. Its one tool can do none of that, even though the instructions say to offer only what the tools provide. The troubleshooting list at the end has more on this.


[05]

Connect a remote MCP server over HTTP

stdio is perfect while you build. Once several agents need the same server, or it lives on another machine, run it over HTTP instead. On the server, that's a one-line change at the bottom of orders_server.py:

Pythonorders_server.py
if __name__ == "__main__":
    server.run(transport="http", host="127.0.0.1", port=8080)

Start it in its own terminal with python orders_server.py. It now listens at http://127.0.0.1:8080/mcp. In your agent, swap the stdio spec for an HTTP one that points at that address:

Pythonagent.py
from promptise.config import HTTPServerSpec

servers = {
    "orders": HTTPServerSpec(url="http://127.0.0.1:8080/mcp"),
}

Nothing else changes. The agent finds the same tool and answers the same way.

Over stdio, the agent starts orders_server.py itself as a child process, for local tools and development. Over HTTP, the orders server runs on its own at 127.0.0.1:8080/mcp and one or more agents connect to it by URL, for shared services and production.
FigureHow the agent reaches the orders server over stdio and over HTTP

[06]

Use several MCP servers in one agent

Real agents rarely live on one server. Add as many as you need to servers and Promptise merges their tools into one list for the model.

Here the agent uses your orders server over HTTP, plus mcp-server-time, an open-source server from the MCP project. uvx, which comes with uv, downloads and starts it for you.

Pythonagent.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import asyncio

from promptise import build_agent
from promptise.config import HTTPServerSpec, StdioServerSpec


async def main():
    agent = await build_agent(
        model="openai:gpt-5-mini",
        servers={
            # Your own server, already running over HTTP.
            "orders": HTTPServerSpec(url="http://127.0.0.1:8080/mcp"),
            # An open-source server from the MCP project, started on demand.
            "time": StdioServerSpec(command="uvx", args=["mcp-server-time"]),
        },
        instructions=(
            "You are a friendly support assistant. Use your tools to answer "
            "questions about orders. Only offer help your tools can provide."
        ),
        trace_tools=True,
    )
    try:
        print("Tools:", agent.tool_names)
        result = await agent.ainvoke(
            {"messages": [{"role": "user", "content": "How many days until order A-1001 arrives?"}]}
        )
        print(result["messages"][-1].content)
    finally:
        await agent.shutdown()


asyncio.run(main())
Output
Tools: ['get_order_status', 'get_current_time', 'convert_time']
→ Invoking tool: get_order_status with {'order_id': 'A-1001'}
✔ Tool result from get_order_status: {"order_id": "A-1001", "status": "shipped", "carrier": "DHL", "eta": "2026-10-14"}
→ Invoking tool: get_current_time with {'timezone': 'Europe/Zurich'}
✔ Tool result from get_current_time: {
  "timezone": "Europe/Zurich",
  "datetime": "2026-10-11T11:41:10+02:00",
  "day_of_week": "Sunday",
  "is_dst": true
}
Your order A-1001 is expected on 2026-10-14. Today is 2026-10-11 (Europe/Zurich), so that’s about 3 days until delivery. It’s currently marked as shipped with carrier DHL. Would you like me to check updates later or convert the ETA to a different timezone?

No single server could answer that question. The agent asked the orders server for the delivery date and the time server for today's date, then did the subtraction itself. In this run the model asked one server after the other. When it asks for both in the same turn, Promptise runs the two calls in parallel, so both start before either result comes back. That's the real payoff of MCP: small, focused servers that combine into something more capable.

Rendering diagram…

Tip

Give every tool a distinct name across all your servers. If two servers both offer a tool with the same name, the agent keeps only the copy from the server listed last in servers and logs a Tool name collision warning, so the other server's tool is never called.


[07]

Connect to an MCP server that needs an API key

A server on a network should know who's calling. Promptise servers can check an API key before they answer anything:

Pythonorders_server.py
1
2
3
4
5
6
7
8
import os

from promptise.mcp.server import APIKeyAuth, AuthMiddleware, MCPServer

server = MCPServer("orders", require_auth=True)
server.add_middleware(
    AuthMiddleware(APIKeyAuth(keys={os.environ["ORDERS_API_KEY"]: "support-agent"}))
)

require_auth=True puts every tool behind the key. A client without a valid key gets 401 Unauthorized and never sees the tool list.

On the agent side, pass the key to the spec. Promptise sends it in the x-api-key header:

Pythonagent.py
1
2
3
4
5
6
7
8
9
10
import os

from promptise.config import HTTPServerSpec

servers = {
    "orders": HTTPServerSpec(
        url="http://127.0.0.1:8080/mcp",
        api_key=os.environ["ORDERS_API_KEY"],
    ),
}

If your server uses JSON Web Tokens from an identity provider instead, pass bearer_token= and Promptise sends it as Authorization: Bearer …. Either way, keep keys in environment variables or a secret manager, never in your code. Authentication & Security covers JWTs, roles and per-tool guards. Build an authenticated MCP server for your AI agent walks through one project end to end.


[08]

When the agent doesn't use your tools

Most connection problems come down to one of these:

  • The tool is never called. The model doesn't understand when it's useful. Rewrite the docstring's first paragraph so it says plainly what the tool does and when to use it. With dozens of tools, see too many MCP tools.

  • The stdio server isn't found. Relative paths in args are resolved from the folder you run the agent in. Use an absolute path, or set cwd= on StdioServerSpec.

  • The model offers things it can't do. Models like to be helpful. Say what the agent may and may not offer in instructions, and keep in mind that the model still words its own replies.

  • Nothing happens with a local model. The model has to support tool calling. With Ollama, pick a model that does.

  • The HTTP server refuses the connection. build_agent stops with an MCPConnectionRejectedError that names the server and the status, for example Server 'orders' rejected the connection: 401 Unauthorized. A 401 or 403 means the key or token on the spec doesn't match the server's. If the URL doesn't end in /mcp, you get the same error with 404 Not Found and a hint: Check the URL (…); Promptise servers serve MCP at /mcp.


[09]

Frequently asked questions

What is an MCP server?

A program that offers tools, data or prompts to AI applications through the Model Context Protocol. Anything that speaks MCP can use it: your own agent, Claude Desktop, an IDE assistant. You write the integration once and every client can use it. What is MCP? explains the protocol in more depth.

Do I need Promptise to use MCP?

No. MCP is an open protocol, and any MCP client can connect to the servers in this guide. Promptise Foundry is a framework for the agent around those connections: reasoning, memory, guardrails, human approval and a runtime for production. Its MCP client is built in, so connecting servers takes one argument.

Which models can I use?

Any model with tool calling. Promptise ships with providers for OpenAI, Anthropic, Google Gemini and Vertex AI, Azure, Amazon Bedrock, Ollama, Mistral, Groq, OpenRouter and more. You switch by changing the model string, for example anthropic:claude-sonnet-5-5 or ollama:llama3.1.

Should I use stdio or HTTP?

Start with stdio: there's nothing to deploy and the agent manages the server for you. Move to HTTP when a server needs to be shared between agents, run on another machine, or sit behind authentication. MCP transports compared goes into stdio, Streamable HTTP and SSE.

Can I turn my existing REST API into an MCP server?

Yes. If your API has an OpenAPI spec, MCPcast generates a complete MCP server from it, with read-only defaults and human approval on anything that writes.

Is it safe to let an agent call tools?

It's as safe as the server makes it. Keep each server's tools narrow, require authentication, and ask a human before anything that changes data. Promptise servers support all three, including approval gates that pause a tool call until someone says yes.


[10]

Where to go next

  • Build a production MCP server in Python: auth, middleware and deployment for the server side.

  • Test an MCP server in Python: pytest patterns for your tools.

  • Quick Start: the shortest path from install to a working agent.

  • Server configuration: every option on StdioServerSpec and HTTPServerSpec.

  • MCP server fundamentals: resources, prompts, routers and middleware.

  • Deployment: running MCP servers in production.

  • Promptise Foundry on GitHub: the source, open under Apache 2.0.

← PreviousMCP Tools vs Resources vs Prompts (With Python Examples)Next lesson →Build a Production MCP Server in Python (Step by Step)