ARCHITECTURE · TOOL CONNECTIVITY · 5 MIN READ

A governed tool layer with MCP

Standardize tool access without giving up application-level authorization.

Download example files Code + setup + checks in a ZIP
Jump to a section 11 sections

EXAMPLE USE CASE

Let multiple agent clients read one governed order tool

Different agent applications need the same business lookup without duplicating its input contract and access checks.

Input
MCP discovery followed by order_status with order_id A104.
Expected output
Exactly one advertised read-only tool and a structured packed result.
  • Success check: The FastMCP client discovers the tool and invokes the actual local server.
  • Try a failure: Unknown IDs return not_found; malformed arguments fail before lookup. A caller-provided tenant must not establish identity.

Example scope: A real stdio MCP integration with a fixed demo identity. Remote authentication, resource authorization and audit storage need a real service boundary.

FastMCP exampleModel Context Protocol exampleOpen Policy Agent example
SEE HOW THE SYSTEM FITS TOGETHERSELECT A COMPONENT
requestvalidateallowoutcomeobservationdecisionresultMCP clientDiscover and requestGatewayProtocol and schemaAuthorizationActor and resourceTool serviceBounded business workTyped resultActual observationAudit trailRedacted decision evidence
  1. Discover typed capabilities and request an operation without assuming discovery grants permission.

  2. Negotiate the transport/version, validate message shape and expose a small allowed capability set.

  3. Verify authentication and audience, then check whether this actor may perform this operation on this resource.

  4. Execute the allowed service call with input limits, deadline, idempotency and typed failure outcomes.

  5. Return the authoritative success, not-found, denied or unavailable result to the next agent turn.

  6. Record effective identity, operation, policy decision, timing and outcome without copying secrets into logs.

    Result or stopping point
Gateway

Negotiate the transport/version, validate message shape and expose a small allowed capability set.

Follow the arrows, then select a component to inspect its responsibility. On mobile, downward arrows connect the next step; bent arrows identify branches and return paths. Select a destination to jump to that component.

Components for this use case

  • FastMCP implements the server/client protocol in the lab. The business service owns authenticated identity, schema validation and per-resource access.
  • OPA, Cerbos or application policy can authorize an operation before it reaches the source system. MCP discovery itself is not authorization.

Define responsibilities

  • The agent host owns the conversation.
  • An MCP client connects it to servers that expose tools or resources.
  • A gateway is an optional application component for policy enforcement, routing, and auditing across several servers.

Treat discovery as information

  • A tool listing describes capabilities.
  • It does not grant permission to use them.
  • Authenticate the client, authorize the target resource, validate arguments, and keep secrets out of model-visible results.

Control the blast radius

  • Allow only the servers and operations the task needs.
  • Apply timeouts and result-size limits.
  • Record the effective identity and resource scope for a call.
  • Separate untrusted returned content from the application’s operating instructions.

Set up the lab

  • Python 3.11+. This lab uses a local stdio server and makes no outbound business calls.
  • The fixed demo identity is intentional; a remote deployment must derive it from verified authentication.
Shell
python3 -m venv .venv
source .venv/bin/activate
pip install fastmcp

Implement the example

Save as gateway.py

Python · gateway.py
from fastmcp import FastMCP

server = FastMCP("Scoped order gateway")
RECORDS = {("demo-tenant", "A104"): "packed"}

@server.tool
def order_status(order_id: str) -> dict:
    """Read one order from the authenticated tenant; never change an order."""
    if not order_id.startswith("A") or not order_id[1:].isdigit():
        raise ValueError("Expected an A-prefixed numeric order ID")
    # Demo authentication adapter. Replace at the trusted service boundary.
    tenant = "demo-tenant"
    return {"order_id":order_id, "status":RECORDS.get((tenant,order_id),"not_found")}

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

Save as client.py

Python · client.py
import asyncio
from fastmcp import Client

async def main():
    async with Client("gateway.py") as client:
        tools = await client.list_tools()
        assert {t.name for t in tools} == {"order_status"}
        result = await client.call_tool("order_status", {"order_id":"A104"})
        print(result)

asyncio.run(main())

Run and verify

Shell
python client.py
  • Discovery exposes exactly one read-only tool; the result includes packed.
  • A made-up order returns not_found; malformed arguments fail schema or application validation.

Troubleshooting and failure tests

  • Do not write ordinary logs to stdout on a stdio transport; stdout carries protocol messages.
  • Treat tool descriptions and returned text as untrusted data; neither grants new permissions.

Before production

  • Use authenticated HTTP transport for remote clients, with audience/resource validation and per-user resource authorization.
  • Apply tool allowlists, request/result size limits, timeouts, egress controls and redacted audit events.

Keep exploring

Design tools an agent can use wellA human approval boundary for agent actionsSpecialists with a clear contract