|
| 1 | +"""Tiny MCP servers the examples share, so each example stays about one idea. |
| 2 | +
|
| 3 | +Nothing here is specific to LangChain — these are plain FastMCP servers. The |
| 4 | +`run_*` functions exist because a server reached over stdio or HTTP has to be |
| 5 | +started as its own process, and that entry point cannot be a lambda. |
| 6 | +""" |
| 7 | + |
| 8 | +from __future__ import annotations |
| 9 | + |
| 10 | +import json |
| 11 | +import os |
| 12 | +from pathlib import Path |
| 13 | + |
| 14 | +from fastmcp import Context, FastMCP |
| 15 | +from fastmcp.server.auth.providers.jwt import JWTVerifier, RSAKeyPair |
| 16 | +from fastmcp.server.dependencies import get_access_token |
| 17 | +from mcp.types import ( |
| 18 | + ElicitRequest, |
| 19 | + ElicitRequestFormParams, |
| 20 | + ElicitResult, |
| 21 | + InputRequiredResult, |
| 22 | + TextContent, |
| 23 | + ToolAnnotations, |
| 24 | +) |
| 25 | +from pydantic import SecretStr |
| 26 | + |
| 27 | + |
| 28 | +def weather_server() -> FastMCP[None]: |
| 29 | + """A server with one tool that always succeeds.""" |
| 30 | + mcp: FastMCP[None] = FastMCP("weather") |
| 31 | + |
| 32 | + @mcp.tool |
| 33 | + def get_forecast(city: str) -> str: |
| 34 | + """Report the forecast for a city.""" |
| 35 | + return f"{city}: 18C and clear." |
| 36 | + |
| 37 | + return mcp |
| 38 | + |
| 39 | + |
| 40 | +def calculator_server() -> FastMCP[None]: |
| 41 | + """A server whose tool reports failure for input it cannot handle.""" |
| 42 | + mcp: FastMCP[None] = FastMCP("calculator") |
| 43 | + |
| 44 | + @mcp.tool |
| 45 | + def divide(numerator: float, denominator: float) -> str: |
| 46 | + """Divide two numbers.""" |
| 47 | + if denominator == 0: |
| 48 | + # Raising inside a tool becomes an MCP error result (`isError=True`) |
| 49 | + # rather than a transport failure, which is what lets the agent see |
| 50 | + # it and retry. See `tool_errors.py`. |
| 51 | + msg = "Cannot divide by zero. Choose a non-zero denominator." |
| 52 | + raise ValueError(msg) |
| 53 | + return str(numerator / denominator) |
| 54 | + |
| 55 | + return mcp |
| 56 | + |
| 57 | + |
| 58 | +def files_server() -> FastMCP[None]: |
| 59 | + """A server with a read-only tool and a destructive one. |
| 60 | +
|
| 61 | + `delete_file` sets `destructiveHint=True`; the adapter surfaces that as |
| 62 | + `metadata["mcp"]["tool"]["annotations"]["destructive_hint"]`, which |
| 63 | + `destructive_interrupt.py` uses to gate the tool behind human approval. |
| 64 | + """ |
| 65 | + mcp: FastMCP[None] = FastMCP("files") |
| 66 | + |
| 67 | + @mcp.tool |
| 68 | + def list_files() -> list[str]: |
| 69 | + """List the files in the workspace.""" |
| 70 | + return ["report.md", "notes.txt"] |
| 71 | + |
| 72 | + @mcp.tool(annotations=ToolAnnotations(destructiveHint=True)) |
| 73 | + def delete_file(path: str) -> str: |
| 74 | + """Delete a file from the workspace.""" |
| 75 | + return f"Deleted {path}." |
| 76 | + |
| 77 | + return mcp |
| 78 | + |
| 79 | + |
| 80 | +def booking_server() -> FastMCP[None]: |
| 81 | + """A server whose tool cannot finish without an answer from a human. |
| 82 | +
|
| 83 | + Uses the guard pattern: the tool checks whether the answer it needs has |
| 84 | + arrived and, if not, returns an `InputRequiredResult` describing the |
| 85 | + question instead of doing any work. Returning early is what makes the call |
| 86 | + safe to replay when the run resumes. |
| 87 | + """ |
| 88 | + mcp: FastMCP[None] = FastMCP("booking") |
| 89 | + |
| 90 | + @mcp.tool |
| 91 | + async def book_table(party_size: int, ctx: Context) -> list[TextContent] | InputRequiredResult: |
| 92 | + """Book a restaurant table. Asks the user which date to book.""" |
| 93 | + answers = ctx.input_responses |
| 94 | + if not answers or "date" not in answers: |
| 95 | + return InputRequiredResult( |
| 96 | + input_requests={ |
| 97 | + "date": ElicitRequest( |
| 98 | + method="elicitation/create", |
| 99 | + params=ElicitRequestFormParams( |
| 100 | + mode="form", |
| 101 | + message="What date would you like to book?", |
| 102 | + requested_schema={ |
| 103 | + "type": "object", |
| 104 | + "properties": {"date": {"type": "string", "format": "date"}}, |
| 105 | + "required": ["date"], |
| 106 | + }, |
| 107 | + ), |
| 108 | + ) |
| 109 | + }, |
| 110 | + request_state="awaiting-date", |
| 111 | + ) |
| 112 | + |
| 113 | + answer = answers["date"] |
| 114 | + if not isinstance(answer, ElicitResult) or answer.action != "accept" or not answer.content: |
| 115 | + return [TextContent(type="text", text="No date given, so nothing was booked.")] |
| 116 | + date = answer.content["date"] |
| 117 | + return [TextContent(type="text", text=f"Booked a table for {party_size} on {date}.")] |
| 118 | + |
| 119 | + return mcp |
| 120 | + |
| 121 | + |
| 122 | +def run_weather_stdio() -> None: |
| 123 | + """Entry point for a weather server spoken to over stdio.""" |
| 124 | + weather_server().run() |
| 125 | + |
| 126 | + |
| 127 | +def run_calculator_stdio() -> None: |
| 128 | + """Entry point for a calculator server spoken to over stdio.""" |
| 129 | + calculator_server().run() |
| 130 | + |
| 131 | + |
| 132 | +def run_weather_http(host: str, port: int) -> None: |
| 133 | + """Entry point for a weather server served over HTTP.""" |
| 134 | + weather_server().run( |
| 135 | + transport="http", host=host, port=port, show_banner=False, log_level="warning" |
| 136 | + ) |
| 137 | + |
| 138 | + |
| 139 | +def run_calculator_http(host: str, port: int) -> None: |
| 140 | + """Entry point for a calculator server served over HTTP.""" |
| 141 | + calculator_server().run( |
| 142 | + transport="http", host=host, port=port, show_banner=False, log_level="warning" |
| 143 | + ) |
| 144 | + |
| 145 | + |
| 146 | +ISSUER = "https://demo.issuer" |
| 147 | +AUDIENCE = "mcp-fleet" |
| 148 | + |
| 149 | + |
| 150 | +def _load_or_generate_keys() -> RSAKeyPair: |
| 151 | + """Return one keypair shared across processes, or a fresh one per process. |
| 152 | +
|
| 153 | + A single process (the `run_server_in_process` examples) can generate its |
| 154 | + own keypair and pass its public half to the server. A multi-process demo |
| 155 | + cannot: the `langgraph dev` worker that mints tokens and the server process |
| 156 | + that verifies them are different interpreters. Point both at the same PEM |
| 157 | + file via `MCP_DEMO_KEYFILE` and they share one keypair; leave it unset and |
| 158 | + every process keeps its own, exactly as before. |
| 159 | + """ |
| 160 | + keyfile = os.environ.get("MCP_DEMO_KEYFILE") |
| 161 | + if keyfile: |
| 162 | + data = json.loads(Path(keyfile).read_text()) |
| 163 | + return RSAKeyPair(private_key=SecretStr(data["private_key"]), public_key=data["public_key"]) |
| 164 | + return RSAKeyPair.generate() |
| 165 | + |
| 166 | + |
| 167 | +_KEYS = _load_or_generate_keys() |
| 168 | +"""Stands in for an identity provider, so the examples can mint real tokens.""" |
| 169 | + |
| 170 | +PUBLIC_KEY = _KEYS.public_key |
| 171 | +"""Pass this to `run_guarded_server`; see why in its docstring.""" |
| 172 | + |
| 173 | + |
| 174 | +def token_for(user: str) -> str: |
| 175 | + """Mint an access token identifying `user`. |
| 176 | +
|
| 177 | + The stand-in for whatever a deployment already has: an OAuth gateway that |
| 178 | + exchanges for a per-user token, or a provider from `fastmcp.client.auth` — |
| 179 | + `OAuth(mcp_url=..., token_storage=<per-user store>)` runs the full |
| 180 | + authorization-code flow per identity, which `auth_oauth.py` demonstrates. |
| 181 | + """ |
| 182 | + return _KEYS.create_token(subject=user, issuer=ISSUER, audience=AUDIENCE) |
| 183 | + |
| 184 | + |
| 185 | +def run_guarded_server(host: str, port: int, name: str, public_key: str) -> None: |
| 186 | + """Serve a token-guarded server whose one tool reports who called it. |
| 187 | +
|
| 188 | + The key is a parameter rather than read from this module: the server runs |
| 189 | + in its own process, which re-imports this file and would otherwise mint a |
| 190 | + second, unrelated key pair. |
| 191 | + """ |
| 192 | + mcp: FastMCP[None] = FastMCP( |
| 193 | + name, |
| 194 | + auth=JWTVerifier(public_key=public_key, issuer=ISSUER, audience=AUDIENCE), |
| 195 | + # Opt into client-side response caching (SEP-2549): the server stamps |
| 196 | + # each cacheable result with this TTL and a `private` scope, so a client |
| 197 | + # holding a `CacheConfig` can serve a repeat `tools/list` from its own |
| 198 | + # store instead of the wire. Without these hints the server sends |
| 199 | + # `ttlMs: 0` and nothing caches, which is why arbitrary third-party |
| 200 | + # servers cannot be relied on for this. |
| 201 | + cache_ttl=60, |
| 202 | + cache_scope="private", |
| 203 | + ) |
| 204 | + |
| 205 | + @mcp.tool |
| 206 | + def whoami() -> str: |
| 207 | + """Report the identity the server derived from the access token.""" |
| 208 | + token = get_access_token() |
| 209 | + return "unauthenticated" if token is None else str(token.claims.get("sub")) |
| 210 | + |
| 211 | + mcp.run(transport="http", host=host, port=port, show_banner=False, log_level="warning") |
0 commit comments