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 20 / 100
20%

Build a Production MCP Server in Python (Step by Step)

Build an MCP server in Python ready for real agents: typed tools, clear errors, API keys with roles, rate limits, a tamper-evident audit log and tests.

Intermediate18 minModel Context Protocol (MCP)Authentication and Access ControlEvals and Testing
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. ✓How 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. ✓How 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

A first MCP server takes ten lines. A server you'd let real agents use takes a bit more thought: it has to tell the model exactly what each tool expects, refuse bad input, know who is calling, keep some callers out of some tools, survive a flood of requests, and leave a record of what happened. This guide builds a small help desk server in Python with Promptise Foundry and adds each of those, one step at a time. At the end you'll have a test suite, a real agent using the server, and an audit log you can prove nobody edited. Every output below is what a real run printed, with gpt-5-mini as the agent's model.

[01]

How do you build an MCP server in Python?

Install Promptise Foundry, create an MCPServer, and turn functions into tools with a decorator:

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

server = MCPServer("helpdesk")

TICKETS = {
    "T-101": {"subject": "Login fails after a password reset", "status": "open"},
    "T-102": {"subject": "Invoice shows the wrong VAT number", "status": "open"},
}


@server.tool()
async def search_tickets(query: str) -> list[dict]:
    """Find support tickets whose subject contains the query."""
    return [
        {"ticket_id": tid, **t}
        for tid, t in TICKETS.items()
        if query.lower() in t["subject"].lower()
    ]


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

That's a working MCP server. The function name becomes the tool name, the type hints become its input schema, and the docstring becomes the description the model reads. server.run() speaks stdio, so a desktop client or an agent can start it directly. The rest of this guide is about what you add before other people's agents depend on it.


[02]

What makes an MCP server production-ready?

Here's the request path you'll end up with. Every call passes through the same checks, in order, before your code runs:

Rendering diagram…

Need

What you use

The model understands each input

Annotated types with Field descriptions and limits

Clear failures

ToolError

Related tools grouped and named

MCPRouter

Knowing who is calling

AuthMiddleware with APIKeyAuth or JWTAuth

Some tools for some callers

roles= or guards= on the tool

Protection from floods and hangs

RateLimitMiddleware, TimeoutMiddleware

A record you can trust

AuditMiddleware

Confidence before you ship

TestClient


[03]

Build the help desk server, step by step

You need Python 3.10 or newer and Promptise Foundry 1.9.0 or newer (pip install "promptise>=1.9.0"). The complete server file is at the end of this section; each step shows the part it adds.

Step 01

Describe every input for the model

The model only sees your tool's name, description and input schema, so put your knowledge there. Annotated with a pydantic Field adds a description and limits to a parameter. A docstring's Args: section works too:

Pythonhelpdesk_server.py
1
2
3
4
5
6
7
8
9
10
11
12
13
TicketId = Annotated[str, Field(description='A ticket ID, for example "T-101".', pattern=r"^T-\d+$")]


@tickets.tool(read_only_hint=True)
async def search(
    query: Annotated[str, Field(description="Words to look for in the ticket subject.", min_length=2)],
    status: Literal["open", "closed"] | None = None,
) -> list[dict]:
    """Find support tickets whose subject contains the query.

    Args:
        status: Only return tickets with this status. Leave it out to search all tickets.
    """

This is the input schema the model receives for search, generated from those few lines:

Output
{'properties': {'query': {'description': 'Words to look for in the ticket subject.', 'minLength': 2, 'title': 'Query', 'type': 'string'}, 'status': {'anyOf': [{'enum': ['open', 'closed'], 'type': 'string'}, {'type': 'null'}], 'default': None, 'description': 'Only return tickets with this status. Leave it out to search all tickets.', 'title': 'Status'}}, 'required': ['query'], 'type': 'object'}

The limits aren't just documentation. Promptise checks them before your function runs, so a malformed ticket ID never reaches your code:

Output
{
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "Invalid input: ticket_id: String should match pattern '^T-\\d+$'",
    "retryable": true,
    "suggestion": "Check the parameter types and constraints in the tool description.",
    ...
Step 02

Fail with a message the model can use

When something legitimately can't be done, raise ToolError with a sentence the model can pass on. It arrives as a structured error, not a crash:

Pythonhelpdesk_server.py
1
2
3
4
5
6
7
@tickets.tool(read_only_hint=True)
async def get(ticket_id: TicketId) -> dict:
    """Get one ticket with its subject, status and customer."""
    ticket = TICKETS.get(ticket_id)
    if ticket is None:
        raise ToolError(f"There is no ticket {ticket_id}.")
    return {"ticket_id": ticket_id, **ticket}
Output
{
  "error": {
    "code": "TOOL_ERROR",
    "message": "There is no ticket T-999.",
    "retryable": false
  }
}
Step 03

Group related tools with a router

As a server grows, routers keep it organised. A router's prefix becomes part of each tool name, so search, get and close on the tickets router reach the model as tickets_search, tickets_get and tickets_close:

Pythonhelpdesk_server.py
tickets = MCPRouter(prefix="tickets")

# ... tools defined with @tickets.tool() ...

server.include_router(tickets)
Step 04

Know who is calling, and limit what they can do

Turn on authentication for the whole server with require_auth=True, and give each caller an API key. The rich key format attaches roles to a key:

Pythonhelpdesk_server.py
1
2
3
4
5
6
7
8
9
10
11
12
server = MCPServer("helpdesk", version="1.0.0", require_auth=True)

server.add_middleware(
    AuthMiddleware(
        APIKeyAuth(
            keys={
                os.environ["HELPDESK_AGENT_KEY"]: {"client_id": "support-bot", "roles": ["agent"]},
                os.environ["HELPDESK_LEAD_KEY"]: {"client_id": "team-lead", "roles": ["agent", "lead"]},
            }
        )
    )
)

Then decide, per tool, who may call it. Closing a ticket is for team leads only:

Pythonhelpdesk_server.py
1
2
3
4
5
6
@tickets.tool(roles=["lead"], destructive_hint=True)
async def close(
    ticket_id: TicketId,
    resolution: Annotated[str, Field(description="One sentence the customer will see.", min_length=10)],
) -> dict:
    """Close a ticket with a resolution. Only team leads can close tickets."""

When the support bot tries anyway, the answer says exactly why:

Output
{
  "error": {
    "code": "ACCESS_DENIED",
    "message": "Requires any of roles [lead], but client has [agent]",
    "retryable": false,
    "details": {
      "guard": "HasRole",
      "tool": "tickets_close"
    }
  }
}

read_only_hint and destructive_hint are standard MCP tool annotations. They tell clients what kind of tool this is, so a client can, for example, ask the user before running a destructive one. If you're using JSON Web Tokens from an identity provider instead of API keys, swap APIKeyAuth for JWTAuth. Authentication & Security covers that, plus scope-based guards.

Step 05

Add rate limits, timeouts and an audit log

Middleware wraps every tool call. It runs in the order you add it, so the first one wraps all the others:

Pythonhelpdesk_server.py
server.add_middleware(LoggingMiddleware())
server.add_middleware(AuthMiddleware(...))  # from step 4
server.add_middleware(RateLimitMiddleware(rate_per_minute=120, per_tool=True))
server.add_middleware(TimeoutMiddleware(default_timeout=10))
server.add_middleware(AuditMiddleware("audit.jsonl", hmac_secret=os.environ["HELPDESK_AUDIT_SECRET"]))
  • RateLimitMiddleware caps how often tools can be called, here 120 calls a minute per tool, so one runaway agent can't flood your backend.

  • TimeoutMiddleware stops any call that takes longer than ten seconds and returns a TIMEOUT error that says the outcome is unknown. Only a read-only or idempotent tool, such as tickets_search, gets retryable: true. For tickets_close, the error tells the agent to check whether the call took effect before it tries again.

  • AuditMiddleware writes one line per call: which tool, which client, which roles, and whether it worked.

Here are the three audit lines from a real run, shortened:

Output
{"timestamp": 1791711456.96081, "tool": "tickets_search", "client_id": "support-bot", "request_id": "c22ca232bdac", "status": "ok", …
{"timestamp": 1791711458.249373, "tool": "tickets_close", "client_id": "support-bot", "request_id": "17ba82af8fbb", "status": "error", …
{"timestamp": 1791711460.048096, "tool": "tickets_get", "client_id": "support-bot", "request_id": "2e96b9bab17f", "status": "ok", …

Each line also carries its position in the chain (seq) and the signature of the line before it, signed with your secret. That makes the log tamper-evident: change a field, delete a line or reorder two, and the chain breaks. A restarted server continues the chain in the same file. Promptise ships a checker; point it at the variable that holds your secret:

>_Terminal
promptise audit verify audit.jsonl --key-env HELPDESK_AUDIT_SECRET

On the untouched log from the agent run below:

Output
OK 3 entries: intact.
last_hash 76faa13af8c0ffcb7139d23ed9903b856c15bdc8d29c420fef213d04f0f7ccab (seq 2)

After changing a single status from ok to error on the first line, and on a copy with the second line deleted:

Output
TAMPERED edited.jsonl:1: modified: the entry was changed after it was signed (its signature no longer matches, the next entry still links to it)
FAILED 3 entries: 1 problem; the first is at edited.jsonl:1.
TAMPERED deleted.jsonl:2: deleted: 1 entry deleted between line 1 and this line (seq 0 -> 2)
FAILED 2 entries: 1 problem; the first is at deleted.jsonl:2.

The command exits with 1 when the log was changed, so it fits a scheduled job or a CI step. In Python, verify_audit_log("audit.jsonl", secret) from promptise.mcp.server returns the same report, with ok, entries and each problem.

Three versions of a three-line audit log. Each line carries the signature of the one before it, so promptise audit verify reports the untouched log as intact, an edited status on line 1 as modified, and a deleted line 2 as a jump from seq 0 to 2.
FigureHow the signed audit chain shows an edited or a deleted line
Warning

Keep hmac_secret somewhere safe; nobody can verify the log without it. If you write a log file without hmac_secret or the PROMPTISE_AUDIT_SECRET environment variable, AuditMiddleware raises ValueError when the server starts, instead of signing with a random key that can't be checked later.

Calls rejected before the audit middleware, such as those without a valid key, don't reach the log. Move AuditMiddleware earlier in the chain if you want those recorded too. Calls with invalid input do reach it: Promptise validates the arguments inside the chain, right before your tool runs, so the audit line records the VALIDATION_ERROR.

Step 06

Test it without starting anything

TestClient runs the full pipeline in memory: validation, authentication, middleware, role checks and your code. Pass request metadata to act as a particular caller:

Pythontest_helpdesk.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
33
34
35
36
37
38
39
40
41
42
43
44
import os

os.environ.setdefault("HELPDESK_AGENT_KEY", "test-agent-key")
os.environ.setdefault("HELPDESK_LEAD_KEY", "test-lead-key")
os.environ.setdefault("HELPDESK_AUDIT_SECRET", "test-audit-secret")

from promptise.mcp.server import TestClient  # noqa: E402

from helpdesk_server import server  # noqa: E402

AGENT = TestClient(server, meta={"x-api-key": "test-agent-key"})
LEAD = TestClient(server, meta={"x-api-key": "test-lead-key"})


async def test_tools_are_listed_with_descriptions():
    tools = {t.name: t for t in await AGENT.list_tools()}
    assert set(tools) == {"tickets_search", "tickets_get", "tickets_close"}
    status = tools["tickets_search"].input_schema["properties"]["status"]
    assert "Only return tickets with this status" in status["description"]


async def test_search_finds_open_login_tickets():
    result = await AGENT.call_tool("tickets_search", {"query": "login", "status": "open"})
    assert "T-101" in result[0].text and "T-103" not in result[0].text


async def test_an_agent_cannot_close_tickets():
    result = await AGENT.call_tool("tickets_close", {"ticket_id": "T-102", "resolution": "Corrected the VAT number."})
    assert "ACCESS_DENIED" in result[0].text


async def test_a_lead_can_close_tickets():
    result = await LEAD.call_tool("tickets_close", {"ticket_id": "T-102", "resolution": "Corrected the VAT number."})
    assert '"status": "closed"' in result[0].text


async def test_bad_input_is_rejected_before_the_handler_runs():
    result = await AGENT.call_tool("tickets_get", {"ticket_id": "101"})
    assert "VALIDATION_ERROR" in result[0].text


async def test_calls_without_a_key_are_refused():
    result = await TestClient(server).call_tool("tickets_get", {"ticket_id": "T-101"})
    assert "AUTHENTICATION" in result[0].text.upper()
Note

list_tools() returns the MCP SDK's own Tool objects, so the schema is input_schema. With the 1.x SDK (pip install "mcp<2") these attributes are camelCase (inputSchema).

Install the test tools and run them. The tests are async, so tell pytest-asyncio to run them automatically:

>_Terminal
pip install pytest pytest-asyncio
pytest -o asyncio_mode=auto
Output
…
test_helpdesk.py ......                                                  [100%]

============================== 6 passed in 0.42s ===============================

Tests like these catch quiet mistakes. If a ticket's subject said "log in", a search for "login" would find nothing, and only a test would tell you.

The complete server

Pythonhelpdesk_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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
import os
from typing import Annotated, Literal

from pydantic import Field

from promptise.mcp.server import (
    APIKeyAuth,
    AuditMiddleware,
    AuthMiddleware,
    LoggingMiddleware,
    MCPRouter,
    MCPServer,
    RateLimitMiddleware,
    TimeoutMiddleware,
    ToolError,
)

server = MCPServer("helpdesk", version="1.0.0", require_auth=True)

# Middleware runs in the order it's added: the first one wraps all the others.
server.add_middleware(LoggingMiddleware())
server.add_middleware(
    AuthMiddleware(
        APIKeyAuth(
            keys={
                os.environ["HELPDESK_AGENT_KEY"]: {"client_id": "support-bot", "roles": ["agent"]},
                os.environ["HELPDESK_LEAD_KEY"]: {"client_id": "team-lead", "roles": ["agent", "lead"]},
            }
        )
    )
)
server.add_middleware(RateLimitMiddleware(rate_per_minute=120, per_tool=True))
server.add_middleware(TimeoutMiddleware(default_timeout=10))
server.add_middleware(AuditMiddleware("audit.jsonl", hmac_secret=os.environ["HELPDESK_AUDIT_SECRET"]))

# A stand-in for your ticketing system.
TICKETS = {
    "T-101": {"subject": "Login fails after a password reset", "status": "open", "customer": "acme"},
    "T-102": {"subject": "Invoice shows the wrong VAT number", "status": "open", "customer": "globex"},
    "T-103": {"subject": "Login page is slow", "status": "closed", "customer": "acme"},
}

TicketId = Annotated[str, Field(description='A ticket ID, for example "T-101".', pattern=r"^T-\d+$")]

tickets = MCPRouter(prefix="tickets")


@tickets.tool(read_only_hint=True)
async def search(
    query: Annotated[str, Field(description="Words to look for in the ticket subject.", min_length=2)],
    status: Literal["open", "closed"] | None = None,
) -> list[dict]:
    """Find support tickets whose subject contains the query.

    Args:
        status: Only return tickets with this status. Leave it out to search all tickets.
    """
    words = query.lower()
    return [
        {"ticket_id": tid, **t}
        for tid, t in TICKETS.items()
        if words in t["subject"].lower() and (status is None or t["status"] == status)
    ]


@tickets.tool(read_only_hint=True)
async def get(ticket_id: TicketId) -> dict:
    """Get one ticket with its subject, status and customer."""
    ticket = TICKETS.get(ticket_id)
    if ticket is None:
        raise ToolError(f"There is no ticket {ticket_id}.")
    return {"ticket_id": ticket_id, **ticket}


@tickets.tool(roles=["lead"], destructive_hint=True)
async def close(
    ticket_id: TicketId,
    resolution: Annotated[str, Field(description="One sentence the customer will see.", min_length=10)],
) -> dict:
    """Close a ticket with a resolution. Only team leads can close tickets."""
    ticket = TICKETS.get(ticket_id)
    if ticket is None:
        raise ToolError(f"There is no ticket {ticket_id}.")
    ticket.update(status="closed", resolution=resolution)
    return {"ticket_id": ticket_id, **ticket}


server.include_router(tickets)

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

[04]

Put a real agent in front of it

Start the server with the three secrets set, and it listens at http://127.0.0.1:8080/mcp. Then connect an agent with the support bot's key. This is the same pattern as in How to Connect MCP Servers to Your AI Agent in Python:

Pythonsupport_agent.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
import asyncio
import os

from promptise import build_agent
from promptise.config import HTTPServerSpec


async def main():
    agent = await build_agent(
        model="openai:gpt-5-mini",
        servers={
            "helpdesk": HTTPServerSpec(
                url="http://127.0.0.1:8080/mcp",
                api_key=os.environ["HELPDESK_AGENT_KEY"],
            ),
        },
        instructions="You are a support assistant. Use the help desk tools.",
        trace_tools=True,
    )
    try:
        result = await agent.ainvoke(
            {"messages": [{"role": "user", "content": "Find the open login ticket and close it as fixed."}]}
        )
        print(">>>", result["messages"][-1].content)
    finally:
        await agent.shutdown()


asyncio.run(main())
Output
→ Invoking tool: tickets_search with {'query': 'login', 'status': 'open'}
✔ Tool result from tickets_search: [{"ticket_id": "T-101", "subject": "Login fails after a password reset", "status": "open", "customer": "acme"}]
→ Invoking tool: tickets_close with {'ticket_id': 'T-101', 'resolution': 'We fixed the login-after-password-reset issue; please try logging in again and let us know if you still see problems.'}
✖ tickets_close error: ACCESS_DENIED: Requires any of roles [lead], but client has [agent]
→ Invoking tool: tickets_get with {'ticket_id': 'T-101'}
✔ Tool result from tickets_get: {"ticket_id": "T-101", "subject": "Login fails after a password reset", "status": "open", "customer": "acme"}
>>> I found the open login ticket (T-101) but was unable to close it because my account lacks the required "lead" role. …

Read it from the top and the rules from this guide show up. The agent found the ticket and went straight to closing it, with a full sentence as the resolution. It never tried a one-word answer, because the model saw that resolution needs at least 10 characters: a Promptise agent's model sees each parameter's limits, like minLength and pattern, not just its type. The server still enforces them for every other client. Then the role check stopped the agent, because the support bot isn't a lead. The refusal shows up as a failed call (✖); the agent looked the ticket up and told the user why it couldn't close it. Nothing in the agent's code mentions any of these rules; they live in the server, where they hold no matter which agent calls.


[05]

Before you deploy

  • Keep secrets out of code. API keys and the audit secret come from environment variables or a secret manager.

  • Put HTTPS in front. Run the server behind a reverse proxy or load balancer that terminates TLS. server.run() binds 127.0.0.1 by default, so only the same machine can reach it. When the proxy runs on another host or the server runs in a container, pass host="0.0.0.0" and allowed_hosts with the hostname your proxy forwards.

  • Use your identity provider in production. API keys suit service-to-service calls. For people and per-user access, use JWTAuth, and see Multi-Tenancy if several customers share one server.

  • Ask a human before risky actions. Mark a tool with requires_approval=True and connect an approver, and each call waits for a person's sign-off. Approval Gates shows how to set it up.


[06]

Frequently asked questions

Do I need async functions for tools?

The examples use async def, which suits tools that call databases or other APIs without blocking. Keep slow, blocking work out of your tools or move it to a background job, so one call doesn't hold up the others.

stdio or HTTP?

Use stdio while you build and for tools that run on the same machine as the client. Use HTTP for anything shared or deployed. Authentication and per-caller roles only make sense over HTTP, where each request carries its own key or token.

How do I see what my server exposes?

Connect any MCP client and list its tools, or call list_tools() on a TestClient as the tests above do. Each tool's description and input schema are exactly what the model will read.

Can I use JWTs instead of API keys?

Yes. JWTAuth validates tokens, puts their roles and scopes on the request, and works with the same roles= and guards. Authentication & Security has the details.


[07]

Where to go next

  • Server fundamentals: tools, resources, prompts and dependency injection.

  • Routers & Middleware: every built-in middleware and how to write your own.

  • Testing: more on TestClient.

  • Production Features and Deployment: caching, health, queues and running in production.

  • OpenAPI to MCP: Turn Any REST API into an MCP Server: generate a server like this from an existing API.

← PreviousHow to Connect MCP Servers to Your AI Agent in PythonNext lesson →MCP Transports: stdio vs Streamable HTTP vs SSE (Python)