diff --git a/pyproject.toml b/pyproject.toml
index 5578902..ff47216 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -7,7 +7,7 @@ authors = [
]
dependencies = [
"wslink>=2.5.8,<3",
- "trame-common>=1.2.7",
+ "trame-common>=1.3.0",
"more-itertools",
]
requires-python = ">=3.10"
diff --git a/src/trame_server/core.py b/src/trame_server/core.py
index d196aed..878af6d 100644
--- a/src/trame_server/core.py
+++ b/src/trame_server/core.py
@@ -72,6 +72,7 @@ def __init__(
self._running_stage = 0 # 0: off / 1: pending / 2: running
self._running_port = 0
self._running_future = None
+ self._server_options = None # set by start()
self._www = None
self.serve = {} # HTTP static endpoints
self._loaded_modules = set()
@@ -80,6 +81,11 @@ def __init__(
self._root_protocol = None
self._protocols_to_configure = []
+ # Agents (MCP): created on first access to self.mcp
+ self._mcp = None
+ self._mcp_bound = False
+ self._mcp_endpoint_mounted = False
+
# ENV variable mapping settings
self.hot_reload = "--hot-reload" in sys.argv or bool(
os.getenv("TRAME_HOT_RELOAD", None)
@@ -107,6 +113,7 @@ def __init__(
commit_fn=self._push_state,
hot_reload=self.hot_reload,
exception_handler=self._handle_exception,
+ get_mcp=self._get_mcp,
)
for key in [
"scripts",
@@ -127,6 +134,7 @@ def __init__(
internal=parent_server._state,
commit_fn=self._push_state,
hot_reload=self.hot_reload,
+ get_mcp=self._get_mcp,
)
# Controller
@@ -452,6 +460,11 @@ def cli(self):
action="store_true",
)
+ # Agents (MCP)
+ from .mcp import MCP # noqa: PLC0415
+
+ MCP.add_arguments(self._cli_parser)
+
CoreServer.add_arguments(self._cli_parser)
return self._cli_parser
@@ -474,6 +487,55 @@ def context(self) -> State:
"""
return self._context
+ @property
+ def mcp(self):
+ """
+ The MCP server agents connect to, created on first access. A child
+ server's is built on its parent's and shares everything with it, as its
+ state and controller do, and the names it exposes objects under go
+ through its translator.
+
+ :return: The server MCP
+ :rtype: trame_server.mcp.MCP
+ """
+ if self._mcp is None:
+ from .mcp import MCP # noqa: PLC0415
+
+ internal = self._parent_server.mcp if self._parent_server else None
+ self._mcp = MCP(self, internal=internal)
+ return self._mcp
+
+ def _get_mcp(self):
+ return self.mcp
+
+ def _bind_mcp(self, wslink_server):
+ """Called once the web server is bound. Mount the MCP endpoint, whether or not
+ self.mcp exists yet or serves http now, since routes freeze at start and the
+ app may add the transport later. It is left out when the launch options keep
+ agents in other processes out for the whole run."""
+ from .mcp.cli import to_launch_options # noqa: PLC0415
+
+ self._mcp_bound = True
+ if not to_launch_options(self.server_options).transports_withheld:
+ from .mcp.endpoint.aiohttp import mount # noqa: PLC0415
+
+ self._mcp_endpoint_mounted = mount(self, wslink_server)
+ if self._mcp is not None:
+ self._mcp._start()
+
+ def _mcp_ready(self):
+ """Called when the server is ready: announce agent access when it is live."""
+ if self._mcp is not None:
+ self._mcp._on_ready()
+ if self._mcp._exposes_anything():
+ return
+ from .mcp.cli import to_launch_options # noqa: PLC0415
+
+ if to_launch_options(self.server_options).enabled:
+ logging.getLogger("trame_server.mcp").warning(
+ "--mcp is given, but this app exposes nothing to agents"
+ )
+
@property
def controller(self) -> Controller:
"""
diff --git a/src/trame_server/mcp/README.md b/src/trame_server/mcp/README.md
new file mode 100644
index 0000000..8b21146
--- /dev/null
+++ b/src/trame_server/mcp/README.md
@@ -0,0 +1,240 @@
+# How `trame_server.mcp` works
+
+This package lets agents use a running trame app through MCP (Model Context
+Protocol). This document explains its implementation, for the people and coding
+agents who change it. What applications write, and why the API looks the way it
+does, is in the **Agents (MCP)** guide of the trame documentation
+(`docs/vitepress/guide/mcp/index.md` in
+[Kitware/trame](https://github.com/Kitware/trame)). Module docstrings have the
+details.
+
+## What it serves
+
+`server.mcp`, an instance of `MCP`, is the MCP server of a trame server. Agents
+get:
+
+- **Tools, resources and prompts** the application declares, with
+ `@server.mcp.tool`, `server.mcp.resource(uri)` and `@server.mcp.prompt`, or
+ the same decorators on a component's methods.
+- **Objects**: instances of classes that inherit `MCPExposable` (from
+ trame-common) and declare what agents see, such as components and
+ trame-dataclass models. The app exposes objects under names
+ (`server.mcp.expose_object()`, `component.mcp_expose()`), and agents reach
+ further objects through their properties. A `state` object has the state keys
+ the app exposes (`state.mcp_expose()`) as properties. Six generic tools, the
+ _object tools_, work on all objects.
+
+Nothing is served unless the app is launched with `--mcp` (`mcp.enabled`).
+Agents in other processes connect through a _transport_: the only one is HTTP,
+at `/mcp` on the trame web server's port. Agents inside the app's process use
+`server.mcp.client()`, under the same rules.
+
+## Package map
+
+| Module | Contents |
+| --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `core.py` | `MCP`: its options, the registries of tools, resources and prompts, and its life cycle |
+| `cli.py` | The launch flags (`--mcp`, ...) and environment variables, read into a `LaunchOptions` |
+| `endpoint/core.py` | `MCPEndpoint`, the HTTP endpoint, independent of any web server: it takes an `HTTPRequest` and returns an `HTTPResponse`. `HTTPTransport` holds its options (`server.mcp.http`) |
+| `endpoint/aiohttp.py` | Serves `MCPEndpoint` on aiohttp, trame's default web server |
+| `protocol.py` | `MCPProtocol`: the JSON-RPC dispatch, independent of the transport |
+| `client.py` | `MCPClient`, the client for agents inside the process |
+| `objects.py` | `ObjectLayer`: what agents reach, and the object tools |
+| `typeinfo.py` | What agents see of a class, and type names |
+| `schema.py` | JSON Schemas from type hints, and validation of what agents send |
+| `budget.py` | Keeps replies under `mcp.max_response_tokens` |
+| `content.py` | Turns return values into MCP content |
+| `permissions.py` | Capabilities the people running the app can deny agents |
+| `progress.py` | Progress notifications |
+| `call_log.py` | The log of what agents call (`--mcp-log`) |
+
+trame-common holds the declaration side and knows nothing about serving: the
+decorators (`trame_common.decorators.mcp`) and `MCPExposable`
+(`trame_common.obj.mcp`). `MCPExposable` stores what a class declares as plain
+data, and gives each instance a process-wide id, `_id` (`"0x1"`, `"0x2"`, ...).
+Types of classes adapt it through its `_mcp_*` hooks: components ask to be held
+weakly (`_mcp_hold_weakly`), and trame-dataclass models give their fields, their
+constructor, and `_mcp_settle()`, which waits for the work a change starts.
+
+## Creation and life cycle
+
+```mermaid
+sequenceDiagram
+ autonumber
+ participant App as Application
+ participant S as trame Server
+ participant W as wslink
+ participant M as MCP
+
+ App->>S: server.mcp (first use)
+ S->>M: MCP(server)
+ Note over M: reads the launch options
+ App->>S: server.start()
+ S->>W: create the web server
+ W->>S: set_server
+ Note over S: _bind_mcp mounts /mcp
+ S->>M: _start()
+ W->>S: port_callback
+ S->>M: _on_ready()
+ Note over M: checks the exposure, prints how to connect
+```
+
+- **Creation.** `server.mcp` is created on first use, and reads the launch
+ options then. What they set holds for the whole run: the app's assignments are
+ ignored (`mcp.locked` names them). Agent access is always set at launch: on
+ with `--mcp`, else off.
+- **Mounting.** Once wslink has created its web server (`set_server`),
+ `Server._bind_mcp` mounts `/mcp` with `endpoint/aiohttp.py`, even if
+ `server.mcp` doesn't exist or isn't enabled yet: aiohttp freezes its routes
+ when it starts. It is left out when the launch options keep agents in other
+ processes out for the whole run (no `--mcp`, or `--mcp-transport none`). The
+ endpoint answers 503 until access is on. wslink's other backends (`generic`,
+ `jupyter`, `tornado`) give trame no HTTP server to mount on.
+- **Start.** `MCP._start()` runs when the server binds its port. From then on,
+ the app may change what `--mcp-mutable` names (`activate`, `transport`,
+ `deny`). If no key was set, it generates the one agents must send
+ (`mcp.http.secret`).
+- **Ready.** Once the port is known (`port_callback`), `MCP._on_ready()` logs
+ likely exposure mistakes (`ObjectLayer.audit`), and prints how to connect if
+ access is on.
+
+An `MCP` created after the server started runs `_start()` and `_on_ready()` from
+its constructor.
+
+**Child servers** (`server.create_child_server()`) share their root's MCP
+server. As for `State` and `Controller`, a child's `server.mcp` is an `MCP`
+built on its parent's, `MCP(server, internal=parent.mcp)`, which takes every
+attribute from it through `share()`, except the translator: a child's object
+names get its prefix, like its state keys. Values that aren't containers, such
+as `enabled`, live in an `_MCPShared` instance, since a plain attribute can't be
+shared by reference.
+
+## Life of a request
+
+Two things to know first:
+
+- **Protocol revisions.** A client of MCP 2026-07-28 names its revision in each
+ request's `_meta`, and has no session. Clients of earlier revisions open with
+ `initialize`, and get a session id. Both are served.
+- **The call lock.** Agent calls run one at a time: `MCPProtocol` holds a lock
+ around each, unless the tool is marked `concurrent` or `mcp.concurrent_calls`
+ is set.
+
+An agent calls a tool over HTTP:
+
+```mermaid
+sequenceDiagram
+ autonumber
+ participant A as Agent
+ participant E as MCPEndpoint
+ participant P as MCPProtocol
+ participant T as Tool
+
+ A->>E: POST /mcp (through endpoint/aiohttp.py)
+ Note over E: Origin, key, enabled and transport on, JSON body
+ E->>P: handle(message)
+ Note over P: enabled, permissions, arguments against the schema
+ P->>T: call, under the call lock, inside "with server.state"
+ T-->>P: return value
+ P-->>E: JSON-RPC response
+ E-->>A: JSON, or Server-Sent Events once progress was reported
+```
+
+- `MCPEndpoint` checks the request before reading its body. The docstring of
+ `endpoint/core.py` gives the reason for each check.
+- `MCPProtocol._execute` runs every tool call. It validates the arguments
+ (`schema.py`). A parameter typed with an object class receives an object id
+ from the agent, which it replaces with the object.
+- `with server.state:` flushes what the tool changed. An HTTP request never
+ triggers a flush by itself, so without it, the changes would neither reach
+ browsers nor run `@state.change` reactions.
+- A request is cancelled when its client disconnects or sends
+ `notifications/cancelled`.
+- `MCPClient` hands its requests to `MCPProtocol.handle()` directly, so every
+ rule after the HTTP checks applies to agents inside the process too.
+
+## The object layer (`objects.py`)
+
+**Exposure.** A name holds what it exposes in one of three ways (`SourceType`):
+strongly, weakly (components, so that exposing one doesn't keep it alive), or as
+a function returning the object, called on every request.
+
+**The graph.** For each call, `ObjectLayer._graph()` computes what agents reach.
+It starts from the named objects and follows the properties agents see that hold
+objects, inside lists, tuples, sets and dict values. The resulting `Graph` maps
+each id to `(object, writable)`. It isn't cached, so it always matches what the
+app holds, with nothing to invalidate; its cost grows with what is reachable.
+
+**Read-only.** A name exposed with `read_only=True` lets agents read what it
+reaches but not change it. An object is writable when a writable path reaches
+it. Reached only through read-only names, it can be read and run its read-only
+methods, and only read-only callables can take it.
+
+**Types.** `typeinfo.py` turns what trame-common stores about a class into what
+agents see, and gives each type a name unique in the app. Members whose
+permissions are denied are left out.
+
+**The object tools** are added on the first exposure, so objects coming and
+going never change the tool list:
+
+| Tool | Does |
+| --------------- | ---------------------------------------------------------------------------------------------- |
+| `object_list` | Lists the names, paged |
+| `object_types` | Indexes the types, or describes types and members |
+| `object_get` | Reads an object, and the objects up to `depth` references away |
+| `object_update` | Writes properties, after validating every value |
+| `object_call` | Calls a method. It takes the call lock itself, so the method's own `concurrent` option decides |
+| `object_batch` | Validates every step, then runs them under one lock |
+
+**Replies** are `{"result", "objects", "more"}`: `result` refers to objects by
+id, and `objects` holds each object read, once. `budget.py` keeps a reply under
+`max_response_tokens` by leaving out the objects farthest from what was read
+first. `more` lists what was cut, with the call that returns it.
+
+**Settling.** After a call or an update, the layer awaits the object's
+`_mcp_settle()`, so that the reply includes what the change derived.
+
+## Design decisions to keep
+
+- `MCPEndpoint` stays independent of the web server, so a host can serve it on
+ its own.
+- The endpoint always requires a key (`mcp.http.secret`), generated at start
+ unless set, even when the server listens on loopback only: other users of the
+ machine reach loopback, and so does a reverse proxy forwarding requests from
+ the network. A page that rebinds its domain to 127.0.0.1 doesn't know the key
+ either. The `Origin` check also stops other web pages, and the JSON body
+ forces a CORS preflight that is never granted.
+- These checks cover `/mcp` only. Browser pages drive the app through a
+ WebSocket that wslink serves on the same port, and it accepts wslink's public
+ default key unless the app is launched with `--authKey` or `--authKeyFile`, so
+ other pages and hosts can drive the app too. Turning on agent access leaves
+ that key alone, so that existing deployments keep working; the connection
+ instructions point it out instead.
+- The MCP key has the WebSocket key's options, `--mcp-auth-key` (`auto` for a
+ random one), `--mcp-auth-key-file`, which wins, and `--mcp-hide-secret`, but
+ stays a separate key: the WebSocket's goes in browser URLs, and an agent
+ holding it could get around `--mcp-deny` through the WebSocket.
+- Clients are never told the tool list changed (`listChanged: false`). It
+ changes only when the app adds or removes a tool, or a permission changes, and
+ a call to a tool no longer offered is refused with the reason.
+- Calls run one at a time by default, and each tool call flushes the state.
+- Replies stay under `max_response_tokens`, and what is cut says how to get it.
+- Nothing is served without `--mcp`: the person running the app decides, not the
+ app. What the launch flags set holds for the whole run unless `--mcp-mutable`
+ names it, and only by name: there is no flag making everything mutable. A key
+ given at launch is never mutable.
+- A `--mcp-deny` name the app doesn't declare refuses every call, so that a typo
+ can't leave something allowed.
+
+## Where to change what
+
+| To | Change |
+| ---------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- |
+| Add a launch flag | `cli.py` (`add_arguments`, `LaunchOptions`, `to_launch_options`), then apply it in `MCP._apply_launch_options` |
+| Add an option to `server.mcp` | A field in `_MCPShared`, and a property on `MCP` |
+| Serve on another web server | A module in `endpoint/` that turns its requests into `HTTPRequest`s for `MCPEndpoint.post`, mounted from `Server._bind_mcp` |
+| Add a transport | Its name in `TRANSPORTS` (`core.py`), and code feeding `MCPProtocol.handle()`, as `client.py` does |
+| Serve a new MCP method | The handler tables in `MCPProtocol.__init__` |
+| Change the object tools or their replies | `objects.py` (their descriptions are its `*_DESCRIPTION` constants), and `budget.py` |
+| Support a new type in signatures | `schema.py`: `type_to_schema`, `validate`, `from_json` |
+| Change what agents see of a class | `typeinfo.py` |
diff --git a/src/trame_server/mcp/__init__.py b/src/trame_server/mcp/__init__.py
new file mode 100644
index 0000000..413c847
--- /dev/null
+++ b/src/trame_server/mcp/__init__.py
@@ -0,0 +1,32 @@
+"""Agent access to trame applications through MCP (Model Context Protocol).
+
+``server.mcp`` is the MCP server of a trame server: it serves the tools,
+resources and prompts an application declares, and the objects it exposes,
+to agents in other processes through its transports (HTTP, on the same port
+as the application) and to agents inside it (``server.mcp.client()``). See
+:class:`trame_server.mcp.core.MCP`.
+"""
+
+from trame_common.obj.mcp import Progress
+
+from trame_server.mcp.client import MCPClient, MCPError
+from trame_server.mcp.content import Image
+from trame_server.mcp.core import MCP, MCPDisabledError
+from trame_server.mcp.endpoint import HTTPTransport, claude_command, codex_command
+from trame_server.mcp.permissions import PermissionDeniedError
+from trame_server.mcp.schema import ToolError, ValidationError
+
+__all__ = [
+ "MCP",
+ "HTTPTransport",
+ "Image",
+ "MCPClient",
+ "MCPDisabledError",
+ "MCPError",
+ "PermissionDeniedError",
+ "Progress",
+ "ToolError",
+ "ValidationError",
+ "claude_command",
+ "codex_command",
+]
diff --git a/src/trame_server/mcp/budget.py b/src/trame_server/mcp/budget.py
new file mode 100644
index 0000000..4e05d5e
--- /dev/null
+++ b/src/trame_server/mcp/budget.py
@@ -0,0 +1,136 @@
+"""Keeping replies small: values nobody asked for are capped, and every
+reply stays within ``mcp.max_response_tokens``.
+
+Whatever is cut short says so in a ``more`` entry, which names the call that
+returns the rest when there is one.
+"""
+
+from __future__ import annotations
+
+import json
+
+__all__ = ["CHARS_PER_TOKEN", "MAX_ITEMS", "MAX_STRING", "cap", "shrink", "size"]
+
+# A rough estimate, good enough to stay under clients' limits
+CHARS_PER_TOKEN = 4
+# Unrequested values: longer lists and strings are cut
+MAX_ITEMS = 20
+MAX_STRING = 400
+# Below this, a string is not worth cutting to fit the budget
+MIN_STRING = 40
+
+
+def size(value) -> int:
+ """The length of ``value`` as the compact JSON text a reply carries."""
+ return len(
+ json.dumps(value, separators=(",", ":"), ensure_ascii=False, default=str)
+ )
+
+
+def _cut_string(text, length):
+ return text[: max(1, length - 1)] + "…"
+
+
+def cap(value):
+ """``(value, note)``: ``value`` with its lists cut to ``MAX_ITEMS`` and
+ its strings to ``MAX_STRING`` characters, at any depth. ``note`` says
+ what was cut (None when nothing was)."""
+ cut = []
+
+ def visit(v, top):
+ if isinstance(v, str):
+ if len(v) > MAX_STRING:
+ cut.append(f"{MAX_STRING} of {len(v)} characters shown" if top else "")
+ return _cut_string(v, MAX_STRING)
+ return v
+ if isinstance(v, list):
+ items = v
+ if len(v) > MAX_ITEMS:
+ cut.append(f"{MAX_ITEMS} of {len(v)} items shown" if top else "")
+ items = v[:MAX_ITEMS]
+ return [visit(i, False) for i in items]
+ if isinstance(v, dict):
+ return {k: visit(i, False) for k, i in v.items()}
+ return v
+
+ result = visit(value, True)
+ if not cut:
+ return result, None
+ notes = [c for c in cut if c]
+ return result, notes[0] if notes else "shortened"
+
+
+def _cuttable(v):
+ return (isinstance(v, list) and len(v) > 1) or (
+ isinstance(v, str) and len(v) > MIN_STRING
+ )
+
+
+def _largest(value):
+ """The path to the node to cut next, or None. Lists and strings are cut, and
+ dicts are walked into, through their largest member each time."""
+ path, node = [], value
+ while True:
+ if isinstance(node, dict):
+ if not node:
+ return None
+ key = max(node, key=lambda k: size(node[k]))
+ if not (_cuttable(node[key]) or isinstance(node[key], (dict, list))):
+ return None
+ path.append(key)
+ node = node[key]
+ continue
+ if isinstance(node, list):
+ if not node:
+ return None
+ sizes = [size(v) for v in node]
+ big = max(range(len(node)), key=sizes.__getitem__)
+ # One item holding most of the list: cut inside it instead
+ inner = node[big]
+ if (
+ sizes[big] * 2 > sum(sizes)
+ and isinstance(inner, (dict, list, str))
+ and (len(node) == 1 or _cuttable(inner))
+ ):
+ path.append(big)
+ node = inner
+ continue
+ return path if len(node) > 1 else None
+ if isinstance(node, str) and len(node) > MIN_STRING:
+ return path
+ return None
+
+
+def shrink(value, budget, totals=None):
+ """``(value, cuts)``: ``value`` (a dict) with its largest lists and
+ strings cut until its JSON fits in ``budget`` characters, or nothing is
+ left to cut. ``cuts`` maps each top-level key cut into to a note.
+ ``totals`` gives the full length of top-level values already cut (by
+ ``cap``), for the notes."""
+ value = json.loads(json.dumps(value, default=str)) # a copy we may cut
+ totals, lengths, cuts = totals or {}, {}, {}
+ while size(value) > budget:
+ path = _largest(value)
+ if not path:
+ break
+ parent = value
+ for key in path[:-1]:
+ parent = parent[key]
+ node = parent[path[-1]]
+ top = path[0]
+ if len(path) == 1:
+ lengths.setdefault(top, totals.get(top, len(node)))
+ if isinstance(node, list):
+ parent[path[-1]] = node[: max(1, len(node) // 2)]
+ else:
+ parent[path[-1]] = _cut_string(node, len(node) // 2)
+ cuts[top] = None
+ for top in cuts:
+ node = value[top]
+ if top in lengths and isinstance(node, list):
+ cuts[top] = f"{len(node)} of {lengths[top]} items shown"
+ elif top in lengths and isinstance(node, str):
+ cuts[top] = f"{len(node) - 1} of {lengths[top]} characters shown"
+ else:
+ cuts[top] = "shortened"
+ return value, cuts
diff --git a/src/trame_server/mcp/call_log.py b/src/trame_server/mcp/call_log.py
new file mode 100644
index 0000000..f307a0a
--- /dev/null
+++ b/src/trame_server/mcp/call_log.py
@@ -0,0 +1,120 @@
+"""The log of what agents call (``--mcp-log``).
+
+Every tool call, resource read and prompt is logged once, when it ends, at
+INFO on this module's logger: what was called, with its arguments
+shortened, how it ended and how long it took. ``--mcp-log`` or
+``TRAME_MCP_LOG`` set the ``trame_server.mcp`` loggers to INFO; where the
+lines go is up to the application's logging configuration, as for any
+other library.
+
+``MCPProtocol.handle`` records who is asking in a context variable, which
+follows the request into the task that runs it. The caller is the start of
+the HTTP session id when there is one, else the name the client gives
+(``clientInfo``), which is how in-process clients and clients of MCP
+2026-07-28 are named.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import contextlib
+import contextvars
+import json
+import logging
+import time
+
+from trame_server.mcp.permissions import PermissionDeniedError
+
+__all__ = ["logged", "request", "shorten"]
+
+logger = logging.getLogger(__name__)
+
+# How much of an argument a line shows
+MAX_STRING = 60
+MAX_ITEMS = 8
+MAX_DEPTH = 3
+MAX_WHAT = 300
+MAX_ERROR = 200
+
+_session = contextvars.ContextVar("trame_mcp_session", default="-")
+
+
+@contextlib.contextmanager
+def request(caller):
+ """Mark the block as handling a request from ``caller`` (None when unknown),
+ so that the calls made in it are logged under that name."""
+ token = _session.set(caller or "-")
+ try:
+ yield
+ finally:
+ _session.reset(token)
+
+
+def shorten(value, depth=0) -> str:
+ """``value`` as compact JSON-like text: bare keys, long strings replaced
+ by their length, long lists and dicts cut, deep nesting elided."""
+ if isinstance(value, str):
+ if len(value) > MAX_STRING:
+ return f""
+ return json.dumps(value)
+ if isinstance(value, dict):
+ if depth >= MAX_DEPTH:
+ return "{...}"
+ items = [
+ f"{k}: {shorten(v, depth + 1)}" for k, v in list(value.items())[:MAX_ITEMS]
+ ]
+ if len(value) > MAX_ITEMS:
+ items.append(f"+{len(value) - MAX_ITEMS}")
+ return "{" + ", ".join(items) + "}"
+ if isinstance(value, (list, tuple)):
+ if depth >= MAX_DEPTH:
+ return "[...]"
+ items = [shorten(v, depth + 1) for v in value[:MAX_ITEMS]]
+ if len(value) > MAX_ITEMS:
+ items.append(f"+{len(value) - MAX_ITEMS}")
+ return "[" + ", ".join(items) + "]"
+ if value is None or isinstance(value, (bool, int, float)):
+ return json.dumps(value)
+ return f"<{type(value).__name__}>"
+
+
+def _describe_error(error) -> str:
+ text = str(error).strip()
+ first = text.splitlines()[0] if text else ""
+ if not isinstance(error, (ValueError, LookupError, PermissionError)):
+ first = f"{type(error).__name__}: {first}" if first else type(error).__name__
+ if len(first) > MAX_ERROR:
+ first = first[: MAX_ERROR - 1] + "…"
+ return first
+
+
+@contextlib.contextmanager
+def logged(item_type, name, arguments=None):
+ """Log the call run in the block when it ends. ``item_type`` is "tool",
+ "resource" or "prompt"."""
+ if not logger.isEnabledFor(logging.INFO):
+ yield
+ return
+ started = time.monotonic()
+ outcome, error = "ok", None
+ try:
+ yield
+ except asyncio.CancelledError:
+ outcome = "cancelled"
+ raise
+ except PermissionDeniedError as e:
+ outcome, error = "denied", e
+ raise
+ except BaseException as e:
+ outcome, error = "error", e
+ raise
+ finally:
+ what = name if item_type == "tool" else f"{item_type} {name}"
+ if arguments:
+ what = f"{what} {shorten(arguments)}"
+ if len(what) > MAX_WHAT:
+ what = what[: MAX_WHAT - 1] + "…"
+ text = f"{what} -> {outcome} {time.monotonic() - started:.2f}s"
+ if error is not None:
+ text += f": {_describe_error(error)}"
+ logger.info("mcp[%s] %s", _session.get(), text)
diff --git a/src/trame_server/mcp/cli.py b/src/trame_server/mcp/cli.py
new file mode 100644
index 0000000..30eceee
--- /dev/null
+++ b/src/trame_server/mcp/cli.py
@@ -0,0 +1,229 @@
+"""The launch options of agent access: the flags ``Server.cli`` accepts
+(``--mcp``, ``--mcp-transport``, ...) and the environment variables that go
+with some of them.
+
+:func:`add_arguments` adds the flags to an argparse parser, and
+:func:`to_launch_options` reads the parsed arguments and the environment
+into :class:`LaunchOptions`, which ``server.mcp`` applies (see
+:class:`trame_server.mcp.core.MCP`). This module doesn't know which
+transports exist: the caller passes them to :func:`add_arguments`.
+
+Agent access is off unless ``--mcp`` is given. What the launch options set
+holds for the whole run: the application's assignments are ignored, except
+for what ``--mcp-mutable`` names, which it may change once the server runs.
+"""
+
+from __future__ import annotations
+
+import argparse
+import os
+from collections.abc import Collection, Mapping
+from dataclasses import dataclass
+
+__all__ = [
+ "MCP_AUTH_KEY_ENV",
+ "MCP_AUTH_KEY_FILE_ENV",
+ "MCP_DENY_ENV",
+ "MCP_LOG_ENV",
+ "MUTABLE_NAMES",
+ "LaunchOptions",
+ "add_arguments",
+ "to_launch_options",
+]
+
+MCP_AUTH_KEY_ENV = "TRAME_MCP_AUTH_KEY"
+MCP_AUTH_KEY_FILE_ENV = "TRAME_MCP_AUTH_KEY_FILE"
+MCP_LOG_ENV = "TRAME_MCP_LOG"
+MCP_DENY_ENV = "TRAME_MCP_DENY"
+
+#: What ``--mcp-mutable`` can name: agent access (``--mcp``), the transports
+#: (``--mcp-transport``) and the denied permissions (``--mcp-deny``)
+MUTABLE_NAMES = ("activate", "transport", "deny")
+
+
+@dataclass(frozen=True)
+class LaunchOptions:
+ """What the person running the application chose at launch. Agent access is
+ always decided at launch; the other options, when left out (None or empty),
+ are the application's choice."""
+
+ #: ``--mcp``: agents may use the application. Without it, access is off
+ enabled: bool = False
+ #: The names given to ``--mcp-transport``, empty for ``none``
+ transports: tuple[str, ...] | None = None
+ #: ``--mcp-auth-key``, else ``TRAME_MCP_AUTH_KEY``: the key itself, or
+ #: ``auto`` for a random one
+ secret: str | None = None
+ #: ``--mcp-auth-key-file``, else ``TRAME_MCP_AUTH_KEY_FILE``: the path of a
+ #: file holding the key, which takes precedence over ``secret``
+ secret_file: str | None = None
+ #: ``--mcp-hide-secret``: print a placeholder instead of the key
+ hide_secret: bool = False
+ #: ``--mcp-log`` or ``TRAME_MCP_LOG``
+ log: bool = False
+ #: The permissions ``--mcp-deny`` and ``TRAME_MCP_DENY`` deny for the
+ #: whole run. Both apply, since each withholds something
+ denied: tuple[str, ...] = ()
+ #: The names given to ``--mcp-mutable`` (:data:`MUTABLE_NAMES`)
+ mutable: tuple[str, ...] = ()
+
+ def sets(self, name) -> bool:
+ """Whether these options set ``name``: ``activate`` (always, since
+ without ``--mcp`` access is off), ``transport``, ``deny`` or ``secret``
+ (by either key flag)."""
+ if name == "activate":
+ return True
+ if name == "transport":
+ return self.transports is not None
+ if name == "deny":
+ return bool(self.denied)
+ if name == "secret":
+ return self.secret is not None or self.secret_file is not None
+ msg = f"Unknown launch option {name!r}"
+ raise ValueError(msg)
+
+ def holds(self, name, started) -> bool:
+ """Whether these options decide ``name`` now, whatever the application
+ assigns: what they set, until the server has ``started``, and then
+ unless ``--mcp-mutable`` names it. The key is never mutable."""
+ return self.sets(name) and not (started and name in self.mutable)
+
+ @property
+ def transports_withheld(self) -> bool:
+ """Whether no transport can be served in this run: agent access, or the
+ transports, are held off for the whole run."""
+ return ("activate" not in self.mutable and not self.enabled) or (
+ "transport" not in self.mutable and self.transports == ()
+ )
+
+
+def to_launch_options(args, environ: Mapping[str, str] | None = None) -> LaunchOptions:
+ """The launch options in ``args``, as parsed by a parser that
+ :func:`add_arguments` set up, and in ``environ`` (default ``os.environ``).
+ A flag missing from ``args``, or ``args`` None, counts as not given. The key
+ file is not read here, nor ``auto`` resolved: ``server.mcp`` does it once."""
+ if environ is None:
+ environ = os.environ
+ transports = getattr(args, "mcp_transport", None)
+ if transports == ("none",):
+ transports = ()
+ return LaunchOptions(
+ enabled=bool(getattr(args, "mcp", False)),
+ transports=transports,
+ secret=getattr(args, "mcp_auth_key", None)
+ or environ.get(MCP_AUTH_KEY_ENV)
+ or None,
+ secret_file=getattr(args, "mcp_auth_key_file", None)
+ or environ.get(MCP_AUTH_KEY_FILE_ENV)
+ or None,
+ hide_secret=bool(getattr(args, "mcp_hide_secret", False)),
+ log=bool(getattr(args, "mcp_log", False) or environ.get(MCP_LOG_ENV)),
+ denied=launch_names(
+ [*(getattr(args, "mcp_deny", None) or ()), environ.get(MCP_DENY_ENV)]
+ ),
+ mutable=tuple(getattr(args, "mcp_mutable", None) or ()),
+ )
+
+
+def launch_names(values) -> tuple[str, ...]:
+ """Names given at launch, each value comma-separated."""
+ return tuple(n.strip() for v in values if v for n in v.split(",") if n.strip())
+
+
+def add_arguments(parser, transports: Collection[str]):
+ """Add the launch options of agent access (``--mcp``, ``--mcp-transport``,
+ ...) to an argparse ``parser``. ``transports`` are the names
+ ``--mcp-transport`` accepts, besides ``none``."""
+ parser.add_argument(
+ "--mcp",
+ dest="mcp",
+ action="store_true",
+ help="""Let agents use the application through MCP. Without it, agent
+ access is off, in other processes and in this one.""",
+ )
+ parser.add_argument(
+ "--mcp-transport",
+ dest="mcp_transport",
+ action=_CommaNames,
+ allowed=(*transports, "none"),
+ metavar="TRANSPORT",
+ default=None,
+ help=f"""How agents outside the process connect, instead of the
+ application's choice: {", ".join(transports)}, or none for
+ agents in the process only. Comma-separated, repeatable.""",
+ )
+ parser.add_argument(
+ "--mcp-mutable",
+ dest="mcp_mutable",
+ action=_CommaNames,
+ allowed=MUTABLE_NAMES,
+ metavar="NAME",
+ default=None,
+ help="""Let the application change, once it runs, what these launch
+ options set: activate (--mcp, or its absence), transport
+ (--mcp-transport), deny (--mcp-deny). Comma-separated,
+ repeatable. Anything else set at launch holds for the whole
+ run.""",
+ )
+ parser.add_argument(
+ "--mcp-auth-key",
+ dest="mcp_auth_key",
+ metavar="KEY",
+ help=f"""Key agents in other processes must send (as a bearer token
+ over HTTP), or set {MCP_AUTH_KEY_ENV}. 'auto', or no key at
+ all, generates a random one on every start.""",
+ )
+ parser.add_argument(
+ "--mcp-auth-key-file",
+ dest="mcp_auth_key_file",
+ metavar="PATH",
+ help=f"""Path to a file holding the key agents must send, or set
+ {MCP_AUTH_KEY_FILE_ENV}. This takes precedence over
+ '--mcp-auth-key'.""",
+ )
+ parser.add_argument(
+ "--mcp-hide-secret",
+ dest="mcp_hide_secret",
+ action="store_true",
+ help="""Do not print the MCP key in the console output (in the
+ commands that connect agents), e.g. when it is logged""",
+ )
+ parser.add_argument(
+ "--mcp-log",
+ dest="mcp_log",
+ action="store_true",
+ help=f"""Log what agents call, at INFO on the trame_server.mcp loggers
+ (or set {MCP_LOG_ENV})""",
+ )
+ parser.add_argument(
+ "--mcp-deny",
+ dest="mcp_deny",
+ action="append",
+ metavar="PERMISSION",
+ default=None,
+ help=f"""Deny agents these permissions. Comma-separated, repeatable (or
+ set {MCP_DENY_ENV})""",
+ )
+
+
+class _CommaNames(argparse.Action):
+ """Parse a flag taking names, comma-separated and repeatable. Each name is
+ checked against ``allowed`` as it is parsed, so that a wrong one fails like
+ any other wrong value. ``none``, when allowed, can't be combined."""
+
+ def __init__(self, option_strings, dest, allowed=(), **kwargs):
+ super().__init__(option_strings, dest, **kwargs)
+ self.allowed = tuple(allowed)
+
+ def __call__(self, parser, namespace, values, option_string=None):
+ names = [*(getattr(namespace, self.dest, None) or ())]
+ names += [n.strip() for n in values.split(",") if n.strip()]
+ unknown = [n for n in names if n not in self.allowed]
+ if unknown:
+ parser.error(
+ f"{option_string}: unknown name {unknown[0]!r} "
+ f"(choose from {', '.join(self.allowed)})"
+ )
+ if "none" in names and len(set(names)) > 1:
+ parser.error(f"{option_string}: none can't be combined with a transport")
+ setattr(namespace, self.dest, tuple(dict.fromkeys(names)))
diff --git a/src/trame_server/mcp/client.py b/src/trame_server/mcp/client.py
new file mode 100644
index 0000000..8579699
--- /dev/null
+++ b/src/trame_server/mcp/client.py
@@ -0,0 +1,143 @@
+"""Agents inside the application's process: ``server.mcp.client()``.
+
+An in-process client needs no transport. It hands the protocol the
+requests an agent connected over a transport would send (MCP 2026-07-28),
+so what it sees and may do is the same: ``mcp.enabled``, permissions,
+argument validation, calls one at a time and the call log all apply.
+"""
+
+from __future__ import annotations
+
+import inspect
+import itertools
+import logging
+
+from trame_server.mcp.protocol import (
+ CAPABILITIES_KEY,
+ CLIENT_INFO_KEY,
+ MODERN_VERSIONS,
+ VERSION_KEY,
+)
+
+logger = logging.getLogger("trame_server.mcp")
+
+__all__ = ["MCPClient", "MCPError"]
+
+# What a 2026-07-28 result carries for transports, not for the caller
+ENVELOPE = ("resultType", "_meta", "ttlMs", "cacheScope")
+
+
+class MCPError(Exception):
+ """Raised for a request the server cannot serve at all, such as a call to an
+ unknown tool. It carries the JSON-RPC error's ``code``, ``message`` and
+ ``data``. A tool that fails still returns a result, with ``isError`` set."""
+
+ def __init__(self, code, message, data=None):
+ super().__init__(message)
+ self.code = code
+ self.message = message
+ self.data = data
+
+
+class MCPClient:
+ """A client for an agent inside the application's process, returned by
+ ``server.mcp.client()``. It lists what agents see and makes the calls
+ they make.
+
+ Results are the dicts MCP defines: a tool's result holds its ``content``,
+ and ``isError`` when the tool failed, which an agent loop hands back to
+ its model. Requests the server cannot serve raise :class:`MCPError`.
+ Cancelling the task that awaits a call cancels the call.
+ """
+
+ def __init__(self, mcp, name="in-process"):
+ self._mcp = mcp
+ self._name = name
+ self._ids = itertools.count(1)
+
+ @property
+ def name(self):
+ """The name this client gives the server, shown in the call log."""
+ return self._name
+
+ @property
+ def instructions(self):
+ """What agents receive when they connect: the application's text,
+ then the generated overview of what it exposes."""
+ return self._mcp._agent_instructions()
+
+ async def list_tools(self) -> list[dict]:
+ """The tools agents may call, each with its ``name``,
+ ``description``, ``inputSchema`` and ``annotations``."""
+ return (await self._request("tools/list"))["tools"]
+
+ async def call_tool(self, name, arguments=None, *, on_progress=None) -> dict:
+ """Call a tool and return its result: ``content``, and ``isError`` when the
+ tool failed.
+
+ With ``on_progress``, the call asks for the progress that its tool or
+ method reports, and each report calls ``on_progress(value, total,
+ message)``, which may be async. These calls run on the event loop, before
+ the call returns.
+ """
+ params = {"name": name, "arguments": arguments or {}}
+ if on_progress is None:
+ return await self._request("tools/call", params)
+
+ async def notify(notification):
+ fields = notification["params"]
+ try:
+ done = on_progress(
+ fields["progress"], fields.get("total"), fields.get("message")
+ )
+ if inspect.isawaitable(done):
+ await done
+ except Exception: # the call goes on without it
+ logger.exception("on_progress failed")
+
+ return await self._request("tools/call", params, notify=notify)
+
+ async def list_resources(self) -> list[dict]:
+ """The resources agents may read, each with its ``uri`` and
+ ``name``."""
+ return (await self._request("resources/list"))["resources"]
+
+ async def read_resource(self, uri) -> list[dict]:
+ """Read a resource. Returns its contents, each with its ``uri``,
+ ``mimeType`` and ``text`` (or ``blob``, base64-encoded bytes)."""
+ return (await self._request("resources/read", {"uri": uri}))["contents"]
+
+ async def list_prompts(self) -> list[dict]:
+ """The prompts agents may get, each with its ``name`` and
+ ``arguments``."""
+ return (await self._request("prompts/list"))["prompts"]
+
+ async def get_prompt(self, name, arguments=None) -> dict:
+ """Get a prompt. Returns its ``messages`` (and ``description``)."""
+ return await self._request(
+ "prompts/get", {"name": name, "arguments": arguments or {}}
+ )
+
+ async def _request(self, method, params=None, notify=None):
+ from trame_server import __version__ # noqa: PLC0415
+
+ rpc_id = next(self._ids)
+ meta = {
+ VERSION_KEY: MODERN_VERSIONS[0],
+ CAPABILITIES_KEY: {},
+ CLIENT_INFO_KEY: {"name": self._name, "version": __version__},
+ }
+ if notify is not None:
+ meta["progressToken"] = rpc_id # unique among its running requests
+ message = {
+ "jsonrpc": "2.0",
+ "id": rpc_id,
+ "method": method,
+ "params": {**(params or {}), "_meta": meta},
+ }
+ # The client itself scopes its request ids, as a session would
+ response = await self._mcp.protocol.handle(message, session=self, notify=notify)
+ if "error" in response:
+ error = response["error"]
+ raise MCPError(error["code"], error["message"], error.get("data"))
+ return {k: v for k, v in response["result"].items() if k not in ENVELOPE}
diff --git a/src/trame_server/mcp/content.py b/src/trame_server/mcp/content.py
new file mode 100644
index 0000000..c4959a6
--- /dev/null
+++ b/src/trame_server/mcp/content.py
@@ -0,0 +1,117 @@
+"""Coercion of Python return values into MCP content: tool results, resource
+contents and prompt messages."""
+
+from __future__ import annotations
+
+import base64
+import json
+from pathlib import Path
+
+__all__ = [
+ "Image",
+ "to_prompt_messages",
+ "to_resource_contents",
+ "to_tool_result",
+]
+
+
+class Image:
+ """An image that a tool returns.
+
+ .. code-block:: python
+
+ @server.mcp.tool
+ def screenshot() -> Image:
+ return Image(png_bytes, mime_type="image/png")
+ """
+
+ def __init__(self, data: bytes, mime_type: str = "image/png"):
+ self.data = data
+ self.mime_type = mime_type
+
+ @classmethod
+ def from_file(cls, path, mime_type=None):
+ path = Path(path)
+ if mime_type is None:
+ ext = path.suffix.lower().lstrip(".")
+ mime_type = f"image/{'jpeg' if ext in ('jpg', 'jpeg') else ext or 'png'}"
+ return cls(path.read_bytes(), mime_type=mime_type)
+
+ def to_content(self):
+ return {
+ "type": "image",
+ "data": base64.b64encode(self.data).decode("ascii"),
+ "mimeType": self.mime_type,
+ }
+
+
+def _default_encoder(value):
+ if isinstance(value, Image):
+ return f""
+ return repr(value)
+
+
+def to_tool_result(value, structured=False) -> dict:
+ """Convert a tool's return value into an MCP ``tools/call`` result.
+
+ Anything but text and images becomes compact JSON text. That includes None,
+ which becomes ``null`` rather than an empty reply that would leave the agent
+ guessing. With ``structured``, a dict is also sent as ``structuredContent``.
+ Clients that show both then put the same value in the agent's context twice
+ (see ``MCP.structured_content``)."""
+ if isinstance(value, Image):
+ return {"content": [value.to_content()]}
+
+ if isinstance(value, str):
+ return {"content": [{"type": "text", "text": value}]}
+
+ if (
+ isinstance(value, (list, tuple))
+ and value
+ and all(isinstance(v, (Image, str)) for v in value)
+ ):
+ return {
+ "content": [
+ v.to_content() if isinstance(v, Image) else {"type": "text", "text": v}
+ for v in value
+ ]
+ }
+
+ text = json.dumps(
+ value, default=_default_encoder, separators=(",", ":"), ensure_ascii=False
+ )
+ result = {"content": [{"type": "text", "text": text}]}
+ if structured and isinstance(value, dict):
+ result["structuredContent"] = value
+ return result
+
+
+def to_error_result(message: str) -> dict:
+ return {
+ "content": [{"type": "text", "text": message}],
+ "isError": True,
+ }
+
+
+def to_resource_contents(uri, value, mime_type=None) -> dict:
+ """Convert a resource's return value into an MCP ``resources/read`` result:
+ bytes as a base64 blob, a string as text, anything else as JSON text."""
+ if isinstance(value, bytes):
+ content = {
+ "uri": uri,
+ "mimeType": mime_type or "application/octet-stream",
+ "blob": base64.b64encode(value).decode("ascii"),
+ }
+ else:
+ if not isinstance(value, str):
+ value = json.dumps(value)
+ content = {"uri": uri, "mimeType": mime_type or "text/plain", "text": value}
+ return {"contents": [content]}
+
+
+def to_prompt_messages(value) -> list:
+ """Convert a prompt's return value into its MCP messages: a string is one
+ user message, anything else is already the list of messages."""
+ if isinstance(value, str):
+ return [{"role": "user", "content": {"type": "text", "text": value}}]
+ return value
diff --git a/src/trame_server/mcp/core.py b/src/trame_server/mcp/core.py
new file mode 100644
index 0000000..bf025d8
--- /dev/null
+++ b/src/trame_server/mcp/core.py
@@ -0,0 +1,790 @@
+"""The MCP server of a trame server: ``server.mcp``."""
+
+from __future__ import annotations
+
+import inspect
+import logging
+import re
+from dataclasses import dataclass, field
+
+from trame_common.obj.mcp import permission_names
+
+from trame_server import auth
+from trame_server.mcp import cli
+from trame_server.mcp.client import MCPClient
+from trame_server.mcp.endpoint import HTTPTransport
+from trame_server.mcp.objects import OBJECT_TOOLS, ObjectLayer
+from trame_server.mcp.permissions import Permissions
+from trame_server.mcp.protocol import MCPProtocol
+from trame_server.mcp.schema import (
+ check_progress,
+ docstring,
+ function_input_schema,
+ parameter_hints,
+ type_to_schema,
+)
+from trame_server.mcp.typeinfo import tool_reference_schema
+from trame_server.utils import share
+
+logger = logging.getLogger("trame_server.mcp")
+
+__all__ = ["MCP", "MCPDisabledError"]
+
+# How agents outside the process can connect (mcp.transports, and the names
+# --mcp-transport accepts)
+TRANSPORTS = ("http",)
+DEFAULT_TRANSPORTS = ("http",)
+
+# Claude Code rejects a tool whose full name mcp____ is longer
+MAX_FULL_TOOL_NAME = 64
+# What the MCP spec allows in a tool name
+TOOL_NAME = re.compile(r"^[A-Za-z0-9_.-]{1,128}$")
+
+LIVE_APP_INSTRUCTIONS = (
+ "A live trame app, shared with its users: they see your changes at once."
+)
+
+
+# What each launch option sets, and its flag, for the messages
+_LAUNCH_OPTIONS = {
+ "activate": ("Agent access", "--mcp"),
+ "transport": ("The transports", "--mcp-transport"),
+ "secret": ("The MCP key", "--mcp-auth-key"),
+}
+
+
+class MCPDisabledError(PermissionError):
+ """Raised for a call made while ``mcp.enabled`` is False."""
+
+
+@dataclass
+class ToolEntry:
+ name: str
+ description: str
+ fn: object
+ input_schema: dict | None = None # None: derived from fn's signature
+ annotations: dict | None = None
+ concurrent: bool = False # runs without the call lock
+ requires: tuple = () # permission names (mcp.permissions)
+ cached_schema: tuple = field(default=(None, None), repr=False)
+
+
+@dataclass
+class ResourceEntry:
+ uri: str
+ name: str
+ description: str | None
+ mime_type: str | None
+ fn: object
+
+
+@dataclass
+class PromptEntry:
+ name: str
+ description: str | None
+ arguments: list
+ fn: object
+
+
+def _tool_annotations(read_only, annotations):
+ result = dict(annotations or {})
+ if read_only:
+ result["readOnlyHint"] = True
+ return result or None
+
+
+def _check_transports(names):
+ unknown = [n for n in names if n not in TRANSPORTS]
+ if unknown:
+ msg = (
+ f"Unknown MCP transport {unknown[0]!r}; available: {', '.join(TRANSPORTS)} "
+ f"(an empty list serves agents in the process only)"
+ )
+ raise ValueError(msg)
+ return tuple(dict.fromkeys(names))
+
+
+@dataclass
+class _MCPShared:
+ """The values every server's MCP sees, shared like ``State``'s status. Values
+ that must be the same for a root server and its child servers go here, since
+ a plain attribute can't be shared by reference."""
+
+ name: str | None = None
+ enabled: bool = False
+ transports: tuple[str, ...] = DEFAULT_TRANSPORTS
+ concurrent_calls: bool = False
+ structured_content: bool = False
+ max_response_tokens: int = 8000
+ instructions: str | None = None
+ launch_options: cli.LaunchOptions = field(default_factory=cli.LaunchOptions)
+ started: bool = False # the server bound its port
+ ready: bool = False # the server is ready
+
+
+class MCP:
+ """The MCP server of a trame server, created on first access to
+ ``server.mcp``. There is one MCP server per root server: a child server's
+ ``server.mcp`` is built on its parent's and shares everything with it, as
+ its state and controller do, except its translator. The names it exposes
+ objects under go through it, as its state keys do.
+
+ It serves what the application declares: first-class tools, resources
+ and prompts (``@server.mcp.tool``, ``server.mcp.resource(uri)``,
+ ``@server.mcp.prompt``), and objects through the six ``object_*`` tools.
+ Objects are the components and models whose class declares something,
+ reached from the names the application exposes, and the ``state`` object.
+ Nothing is served unless the application is launched with ``--mcp``.
+
+ Agents outside the process connect through ``transports``: HTTP by
+ default, on the trame web server's port, with its options on ``http``.
+ Agents inside the process, such as an assistant built into the
+ application, use ``client()``.
+
+ Every option is a settable attribute, and ``configure()`` sets several at
+ once. What the launch options set (``enabled``, ``transports``,
+ ``http.secret`` and the denied permissions) holds for the whole run, except
+ what ``--mcp-mutable`` names, which may change once the server runs
+ (:attr:`locked`).
+ """
+
+ def __init__(self, server, internal=None):
+ """``internal`` is the parent server's MCP, for a child server's, as for
+ its ``State`` and ``Controller``."""
+ self._server = server.root_server
+ self._translator = server.translator
+ self._shared = share(internal, "_shared", _MCPShared())
+ self._tools: dict[str, ToolEntry] = share(internal, "_tools", {})
+ self._resources: dict[str, ResourceEntry] = share(internal, "_resources", {})
+ self._prompts: dict[str, PromptEntry] = share(internal, "_prompts", {})
+ self._permissions = share(internal, "_permissions", Permissions())
+ self._http = share(internal, "_http", HTTPTransport(self))
+ self._objects = share(internal, "_objects", ObjectLayer(self))
+ self._protocol = share(internal, "_protocol", MCPProtocol(self))
+ if internal is not None:
+ return
+
+ self._apply_launch_options()
+ if self._server._mcp_bound: # created once the server was already up
+ self._start()
+ if self._server.running:
+ self._on_ready()
+
+ # -------------------------------------------------------------------------
+ # Life cycle (driven by the trame server)
+ # -------------------------------------------------------------------------
+
+ def _start(self):
+ """Called when the server binds its port. From then on, the application may
+ change what ``--mcp-mutable`` names."""
+ self._shared.started = True
+ self._permissions._start()
+ self._objects.start()
+ for entry in self._tools.values():
+ unknown = [n for n in entry.requires if n not in self._permissions]
+ if unknown:
+ logger.warning(
+ "Tool %s requires undeclared permissions %s; it is never offered",
+ entry.name,
+ unknown,
+ )
+ self._check_length(entry.name, warn=True)
+ if self._server._mcp_endpoint_mounted:
+ self._http._start()
+
+ def _on_ready(self):
+ self._shared.ready = True
+ self._objects.audit()
+ self._http._on_ready()
+
+ # -------------------------------------------------------------------------
+ # Launch options
+ # -------------------------------------------------------------------------
+
+ @staticmethod
+ def add_arguments(parser):
+ """Add the launch options of agent access (``--mcp``, ``--mcp-transport``,
+ ...) to an argparse ``parser`` (:func:`trame_server.mcp.cli.add_arguments`).
+ ``Server.cli`` calls it."""
+ cli.add_arguments(parser, TRANSPORTS)
+
+ def _apply_launch_options(self):
+ """Apply the command line (``Server.cli``) and the environment
+ (:func:`trame_server.mcp.cli.to_launch_options`): ``enabled``,
+ ``transports``, the key agents must send (``http.secret``), the call log
+ and the denied permissions.
+
+ They are the choice of the person running the application, so they
+ take precedence over what the application assigns: for the whole run,
+ or until the server starts for what ``--mcp-mutable`` names.
+ """
+ args, _ = self._server.cli.parse_known_args()
+ launch = self._shared.launch_options = cli.to_launch_options(args)
+ self._shared.enabled = launch.enabled
+ if launch.transports is not None:
+ self._shared.transports = launch.transports
+ if launch.sets("secret"):
+ # Read once, as the WebSocket's: the file wins, and 'auto' is random
+ secret = auth.resolve_secret(launch.secret, launch.secret_file)
+ if not secret:
+ msg = f"The MCP key file {launch.secret_file!r} is empty"
+ raise ValueError(msg)
+ self._http._secret = secret
+ if launch.log:
+ # Like wslink's --debug, this only sets a level: the handlers are
+ # the application's
+ if logger.getEffectiveLevel() > logging.INFO:
+ logger.setLevel(logging.INFO)
+ self._permissions._deny_at_launch(
+ launch.denied, mutable="deny" in launch.mutable
+ )
+
+ def _launch_holds(self, name):
+ """True when the launch options decide ``name`` (``activate``,
+ ``transport`` or ``secret``) now: the application's assignment is then
+ ignored."""
+ shared = self._shared
+ launch = shared.launch_options
+ if not launch.holds(name, shared.started):
+ return False
+ what, flag = _LAUNCH_OPTIONS[name]
+ until = " until the server starts" if name in launch.mutable else ""
+ logger.info(
+ "%s is set at launch (%s)%s; the application's change is ignored",
+ what,
+ flag,
+ until,
+ )
+ return True
+
+ # -------------------------------------------------------------------------
+ # Options
+ # -------------------------------------------------------------------------
+
+ def configure(
+ self,
+ *,
+ name=None,
+ enabled=None,
+ transports=None,
+ concurrent_calls=None,
+ structured_content=None,
+ instructions=None,
+ max_response_tokens=None,
+ ):
+ """Set several options at once; an option left as None is unchanged. This
+ is the same as assigning the attributes one by one. The HTTP transport's
+ options are set with ``http.configure()``."""
+ options = {
+ "name": name,
+ "enabled": enabled,
+ "transports": transports,
+ "concurrent_calls": concurrent_calls,
+ "structured_content": structured_content,
+ "instructions": instructions,
+ "max_response_tokens": max_response_tokens,
+ }
+ for key, value in options.items():
+ if value is not None:
+ setattr(self, key, value)
+
+ @property
+ def server(self):
+ """The trame server this MCP server belongs to (a root server)."""
+ return self._server
+
+ @property
+ def protocol(self):
+ return self._protocol
+
+ @property
+ def name(self):
+ """The name reported to clients and used in the connection commands
+ (default: the trame server's name)."""
+ return self._shared.name or self._server.name
+
+ @name.setter
+ def name(self, value):
+ self._shared.name = value
+
+ @property
+ def enabled(self):
+ """Whether agents can use what the application declares.
+
+ This is the one switch for agent access, whichever way agents connect.
+ While it is False, every call is refused and the HTTP endpoint answers
+ 503. The launch decides it: True with ``--mcp``, else False, for the
+ whole run. With ``--mcp-mutable activate``, the application may change
+ it once the server runs (``"activate"`` leaves :attr:`locked`).
+ """
+ return self._shared.enabled
+
+ @enabled.setter
+ def enabled(self, value):
+ if bool(value) == self._shared.enabled or self._launch_holds("activate"):
+ return
+ self._shared.enabled = bool(value)
+ if self._shared.enabled:
+ self._http._announce()
+
+ @property
+ def locked(self):
+ """The names of the launch options the application cannot change now:
+ ``activate`` (:attr:`enabled`), ``transport`` (:attr:`transports`) and
+ ``deny`` (the permissions ``--mcp-deny`` denies). It is what the launch
+ options set, except, once the server runs, what ``--mcp-mutable`` names.
+ Assignments to a locked option are ignored, so a UI should disable its
+ switches."""
+ shared = self._shared
+ launch = shared.launch_options
+ return tuple(n for n in cli.MUTABLE_NAMES if launch.holds(n, shared.started))
+
+ @property
+ def transports(self):
+ """How agents outside the process connect (default ``("http",)``): a tuple
+ of transport names, empty when only agents inside the process may connect.
+
+ While ``"http"`` is left out, the HTTP endpoint answers 503.
+ ``--mcp-transport`` sets it for the whole run; with ``--mcp-mutable
+ transport``, the application may change it once the server runs. Without
+ the flag, it is the application's choice at any time.
+ """
+ return self._shared.transports
+
+ @transports.setter
+ def transports(self, value):
+ names = _check_transports((value,) if isinstance(value, str) else value)
+ if names == self._shared.transports or self._launch_holds("transport"):
+ return
+ self._shared.transports = names
+ if "http" in names:
+ self._http._announce()
+
+ def client(self, name="in-process"):
+ """A client for an agent inside the application's process
+ (:class:`MCPClient`). It lists and calls what agents may use, without a
+ transport but under the same rules (``enabled``, permissions). ``name``
+ identifies it in the call log."""
+ return MCPClient(self, name)
+
+ @property
+ def http(self):
+ """The HTTP transport's options (:class:`HTTPTransport`): ``path``,
+ ``secret``, ``allowed_origins`` and the read-only ``url``."""
+ return self._http
+
+ @property
+ def permissions(self):
+ """The permissions: capabilities that the people running the application can
+ withhold from agents. ``declare()`` each one, then name the permissions
+ that a tool, method, property or constructor needs with ``requires=``.
+ ``--mcp-deny`` or ``TRAME_MCP_DENY`` deny permissions for the whole run,
+ unless ``--mcp-mutable deny`` (``permissions.locked``)."""
+ return self._permissions
+
+ @property
+ def concurrent_calls(self):
+ """When False (default), agent calls run one at a time, except those
+ declared with ``concurrent=True``. When True, every call may run
+ while others are in progress."""
+ return self._shared.concurrent_calls
+
+ @concurrent_calls.setter
+ def concurrent_calls(self, value):
+ self._shared.concurrent_calls = bool(value)
+
+ @property
+ def structured_content(self):
+ """Whether to also send a tool's dict result as ``structuredContent``
+ (default False). The result is always sent as compact JSON text too."""
+ return self._shared.structured_content
+
+ @structured_content.setter
+ def structured_content(self, value):
+ self._shared.structured_content = bool(value)
+
+ @property
+ def max_response_tokens(self):
+ """The maximum size of a reply from the ``object_*`` tools, in tokens of
+ about 4 characters (default 8000). A reply cut to fit says how to get the
+ rest."""
+ return self._shared.max_response_tokens
+
+ @max_response_tokens.setter
+ def max_response_tokens(self, value):
+ if not isinstance(value, int) or value < 500:
+ msg = (
+ f"max_response_tokens must be an integer of at least 500, got {value!r}"
+ )
+ raise ValueError(msg)
+ self._shared.max_response_tokens = value
+
+ @property
+ def instructions(self):
+ """Text sent to agents when they connect, ahead of the overview trame
+ generates from what the application exposes (default None)."""
+ return self._shared.instructions
+
+ @instructions.setter
+ def instructions(self, value):
+ self._shared.instructions = value
+
+ def _agent_instructions(self):
+ """What clients receive as ``instructions``: the application's own
+ text, then a generated overview."""
+ lines = [LIVE_APP_INSTRUCTIONS, *self._objects.instructions()]
+ denied = self._permissions.denied
+ if denied:
+ names = ", ".join(
+ f"{n} ({self._permissions.description(n)})" for n in denied
+ )
+ lines.append(
+ f"Turned off in this application: {names}. What needs them is not "
+ f"offered, and calls to it are refused."
+ )
+ overview = "\n".join(lines)
+ if self.instructions:
+ return f"{self.instructions.strip()}\n\n{overview}"
+ return overview
+
+ def _check_enabled(self):
+ if not self._shared.enabled:
+ msg = "MCP access is currently disabled by the application"
+ raise MCPDisabledError(msg)
+ self._permissions._check_launch()
+
+ # -------------------------------------------------------------------------
+ # First-class tools, resources and prompts
+ # -------------------------------------------------------------------------
+
+ def tool(
+ self,
+ fn=None,
+ *,
+ name=None,
+ description=None,
+ read_only=False,
+ annotations=None,
+ concurrent=False,
+ requires=None,
+ ):
+ """Make a function, or a bound method, a tool. Use it as a decorator or call
+ it: ``server.mcp.tool(self.screenshot)``.
+
+ The type hints give the input schema. ``Annotated[T, "description",
+ {json-schema}]`` adds a description and constraints, and a parameter
+ typed with a component or model class takes that object's id or name.
+ Results: a ``str`` is sent as text, an ``Image`` as an image (a list of
+ them as several), and anything else as compact JSON text (``null`` for
+ None).
+
+ :param name: the tool name (default: the function's).
+ :param description: the text agents read (default: the docstring).
+ :param read_only: True when it changes nothing (``readOnlyHint``).
+ :param annotations: extra MCP tool annotations.
+ :param concurrent: True to let it run while other agent calls are in
+ progress.
+ :param requires: the permission, or list of permissions, that a call
+ needs.
+ """
+
+ def decorate(f):
+ self._add_tool(
+ f,
+ name=name,
+ description=description,
+ annotations=_tool_annotations(read_only, annotations),
+ concurrent=concurrent,
+ requires=requires,
+ )
+ return f
+
+ if fn is None:
+ return decorate
+ return decorate(fn)
+
+ def resource(self, uri, *, name=None, description=None, mime_type=None):
+ """Serve what a function returns as the resource ``uri``. This returns a
+ decorator; for a method, call it as
+ ``server.mcp.resource(uri)(self.guide)``."""
+
+ def decorate(f):
+ self._add_resource(
+ f, uri=uri, name=name, description=description, mime_type=mime_type
+ )
+ return f
+
+ return decorate
+
+ def prompt(self, fn=None, *, name=None, description=None):
+ """Make a function, or a bound method, a prompt. Use it as a decorator or
+ call it."""
+
+ def decorate(f):
+ self._add_prompt(f, name=name, description=description)
+ return f
+
+ if fn is None:
+ return decorate
+ return decorate(fn)
+
+ def _check_length(self, tool_name, warn=False):
+ full = f"mcp__{self.name}__{tool_name}"
+ if len(full) <= MAX_FULL_TOOL_NAME:
+ return
+ msg = (
+ f"Tool {tool_name!r}: its full name {full!r} has {len(full)} characters; "
+ f"clients such as Claude Code reject more than {MAX_FULL_TOOL_NAME}. "
+ f"Shorten the tool name or mcp.name"
+ )
+ if warn:
+ logger.warning(msg)
+ return
+ raise ValueError(msg)
+
+ def _add_tool(
+ self,
+ fn,
+ name=None,
+ description=None,
+ annotations=None,
+ concurrent=False,
+ requires=None,
+ ):
+ tool_name = name or fn.__name__
+ if tool_name in OBJECT_TOOLS:
+ msg = f"{tool_name!r} is the name of a built-in object tool; choose another"
+ raise ValueError(msg)
+ if tool_name in self._tools:
+ msg = f"A tool named {tool_name!r} is already registered"
+ raise ValueError(msg)
+ if not isinstance(tool_name, str) or not TOOL_NAME.match(tool_name):
+ msg = f"A tool name is 1-128 of A-Z a-z 0-9 _ - (and .), got {tool_name!r}"
+ raise ValueError(msg)
+ if "." in tool_name:
+ logger.warning(
+ "Tool %r: OpenAI-style function calling rejects dots in names",
+ tool_name,
+ )
+ self._check_length(tool_name)
+ check_progress(fn, f"Tool {tool_name!r}")
+ self._tools[tool_name] = ToolEntry(
+ name=tool_name,
+ description=description or docstring(fn) or "",
+ fn=fn,
+ annotations=annotations,
+ concurrent=bool(concurrent),
+ requires=permission_names(requires),
+ )
+
+ def _add_builtin_tool(
+ self, fn, name, description, annotations=None, concurrent=False
+ ):
+ """Add a built-in tool, whose input schema comes from ``fn``'s signature."""
+ self._tools[name] = ToolEntry(
+ name=name,
+ description=description,
+ fn=fn,
+ input_schema=function_input_schema(fn),
+ annotations=annotations,
+ concurrent=concurrent,
+ )
+
+ def _input_schema(self, entry):
+ """The tool's input schema. A schema derived from the signature names object
+ types, so it is computed again whenever they may have changed."""
+ if entry.input_schema is not None:
+ return entry.input_schema
+ from trame_common.obj.mcp import options_version # noqa: PLC0415
+
+ version = options_version()
+ cached_version, schema = entry.cached_schema
+ if cached_version != version:
+ schema = function_input_schema(entry.fn, ref=tool_reference_schema)
+ entry.cached_schema = (version, schema)
+ return schema
+
+ def _add_resource(self, fn, uri, name=None, description=None, mime_type=None):
+ if uri in self._resources:
+ msg = f"A resource with uri {uri!r} is already registered"
+ raise ValueError(msg)
+ self._resources[uri] = ResourceEntry(
+ uri=uri,
+ name=name or fn.__name__,
+ description=description or docstring(fn),
+ mime_type=mime_type,
+ fn=fn,
+ )
+
+ def _add_prompt(self, fn, name=None, description=None):
+ prompt_name = name or fn.__name__
+ if prompt_name in self._prompts:
+ msg = f"A prompt named {prompt_name!r} is already registered"
+ raise ValueError(msg)
+
+ hints = parameter_hints(fn)
+ arguments = []
+ for pname, param in inspect.signature(fn).parameters.items():
+ if pname == "self" or param.kind in (
+ inspect.Parameter.VAR_POSITIONAL,
+ inspect.Parameter.VAR_KEYWORD,
+ ):
+ continue
+ argument = {
+ "name": pname,
+ "required": param.default is inspect.Parameter.empty,
+ }
+ # Annotated[str, "description"], as for tool parameters
+ argument_description = type_to_schema(hints.get(pname)).get("description")
+ if argument_description:
+ argument["description"] = argument_description
+ arguments.append(argument)
+ self._prompts[prompt_name] = PromptEntry(
+ name=prompt_name,
+ description=description or docstring(fn),
+ arguments=arguments,
+ fn=fn,
+ )
+
+ def list_tools(self):
+ """The tools offered to agents: those whose permissions are all allowed.
+ ``get_tool`` finds the other tools too, so that a call to one of them is
+ refused with the reason."""
+ return [t for t in self._tools.values() if self._permissions.allows(t.requires)]
+
+ def get_tool(self, name):
+ return self._tools.get(name)
+
+ def list_resources(self):
+ return list(self._resources.values())
+
+ def get_resource(self, uri):
+ return self._resources.get(uri)
+
+ def list_prompts(self):
+ return list(self._prompts.values())
+
+ def get_prompt(self, name):
+ return self._prompts.get(name)
+
+ # -------------------------------------------------------------------------
+ # Objects
+ # -------------------------------------------------------------------------
+
+ def expose_object(self, source, name, *, description=None, read_only=False):
+ """Expose an object to agents under ``name``.
+
+ :param source: a component or model, or a function that returns one (or
+ None). trame calls the function on every agent request, so
+ ``lambda: self.active`` follows reassignment. A name holds a
+ component weakly and a model strongly.
+ :param name: must start with a letter or an underscore, and ``state`` is
+ reserved. A name that already exposes something else must be
+ withdrawn first, while exposing the same source again updates its
+ options. Like a state key, the name goes through the server's
+ translator: on a child server with the prefix ``left_``, agents see
+ ``left_viewer`` for ``viewer``.
+ :param description: what this object is for in the application. Agents
+ read it next to the name; the class already says what the type is.
+ :param read_only: agents can call only ``read_only`` methods, and write
+ no property, of what they reach only this way. Reached by id, an
+ object is read-only too, unless a writable name (or a function's
+ result under one), or a property of a writable object, also reaches
+ it.
+ """
+ self._objects.expose(source, self._translate(name), description, read_only)
+
+ def unexpose_object(self, name):
+ """Withdraw a name given with :meth:`expose_object`."""
+ self._objects.unexpose(self._translate(name))
+
+ def _translate(self, name):
+ return self._translator.translate_key(name)
+
+ def describe(self, cls):
+ """What agents currently see of ``cls``, as ``object_types`` shows it, or
+ None when it is hidden. Pass ``"State"`` for the state object."""
+ return self._objects.describe_class(cls)
+
+ def _remove_object(self, obj):
+ """Withdraw every name exposing ``obj``."""
+ self._objects.remove(obj)
+
+ def _add_component_tools(self, component):
+ """Add the tools, resources and prompts that a newly built component marks
+ (``@mcp.tool``, ``@mcp.resource``, ``@mcp.prompt``): all of them, or none
+ when one cannot be added."""
+ from trame_common.obj.mcp import ( # noqa: PLC0415
+ PROMPT_MARKER,
+ RESOURCE_MARKER,
+ TOOL_MARKER,
+ first_class_members,
+ )
+
+ cls = type(component)
+ added = []
+ try:
+ for attr, marker, options in first_class_members(cls):
+ fn = getattr(component, attr)
+ if marker == TOOL_MARKER:
+ key = options["name"] or attr
+ self._check_free(self._tools, key, "tool", cls)
+ self._add_tool(
+ fn,
+ name=options["name"],
+ description=options["description"],
+ annotations=_tool_annotations(
+ options["read_only"], options["annotations"]
+ ),
+ concurrent=options["concurrent"],
+ requires=options["requires"],
+ )
+ added.append((self._tools, key))
+ elif marker == RESOURCE_MARKER:
+ key = options["uri"]
+ self._check_free(self._resources, key, "resource", cls)
+ self._add_resource(fn, **options)
+ added.append((self._resources, key))
+ elif marker == PROMPT_MARKER:
+ key = options["name"] or attr
+ self._check_free(self._prompts, key, "prompt", cls)
+ self._add_prompt(fn, **options)
+ added.append((self._prompts, key))
+ except Exception:
+ for registry, key in added:
+ del registry[key]
+ raise
+
+ @staticmethod
+ def _check_free(registry, key, item_type, cls):
+ entry = registry.get(key)
+ owner = getattr(getattr(entry, "fn", None), "__self__", None)
+ if entry is not None and isinstance(owner, cls):
+ msg = (
+ f"{cls.__name__} {owner._id} already added the {item_type} {key!r}: "
+ f"@mcp.tool, @mcp.resource and @mcp.prompt are for components built "
+ f"once. Unbind the first (_unbind_annotated_methods()) before building "
+ f"another, or register per-instance tools with server.mcp.tool()"
+ )
+ raise ValueError(msg)
+
+ def _remove_component_tools(self, component):
+ """Remove what an unbound component added."""
+ for registry in (self._tools, self._resources, self._prompts):
+ for key, entry in list(registry.items()):
+ if getattr(entry.fn, "__self__", None) is component:
+ del registry[key]
+
+ def _expose_state(self, key, **options):
+ self._objects.expose_state(key, **options)
+
+ def _unexpose_state(self, *keys):
+ self._objects.state.unexpose(*keys)
+
+ def _exposes_anything(self):
+ return bool(
+ self._objects.exposes_anything()
+ or self._resources
+ or self._prompts
+ or any(name not in OBJECT_TOOLS for name in self._tools)
+ )
diff --git a/src/trame_server/mcp/endpoint/__init__.py b/src/trame_server/mcp/endpoint/__init__.py
new file mode 100644
index 0000000..d175010
--- /dev/null
+++ b/src/trame_server/mcp/endpoint/__init__.py
@@ -0,0 +1,33 @@
+"""The HTTP transport: the endpoint agents connect to (``server.mcp.http``,
+``/mcp`` by default).
+
+- :mod:`~trame_server.mcp.endpoint.core` is the endpoint, independent of any
+ web server: :class:`MCPEndpoint` takes an :class:`HTTPRequest` and returns
+ an :class:`HTTPResponse`. :class:`HTTPTransport` holds its options.
+- :mod:`~trame_server.mcp.endpoint.aiohttp` serves it on aiohttp, trame's
+ default web server, where the server mounts it when it starts.
+
+The other wslink backends (``generic``, ``jupyter``, ``tornado``) give trame
+no web server to mount it on. The host that owns the HTTP server can route
+requests to ``MCPEndpoint(server)`` itself.
+"""
+
+from trame_server.mcp.endpoint.core import (
+ HTTPRequest,
+ HTTPResponse,
+ HTTPTransport,
+ MCPEndpoint,
+ claude_command,
+ codex_command,
+ is_loopback,
+)
+
+__all__ = [
+ "HTTPRequest",
+ "HTTPResponse",
+ "HTTPTransport",
+ "MCPEndpoint",
+ "claude_command",
+ "codex_command",
+ "is_loopback",
+]
diff --git a/src/trame_server/mcp/endpoint/aiohttp.py b/src/trame_server/mcp/endpoint/aiohttp.py
new file mode 100644
index 0000000..ae2e01e
--- /dev/null
+++ b/src/trame_server/mcp/endpoint/aiohttp.py
@@ -0,0 +1,97 @@
+"""Serve the MCP endpoint on aiohttp, wslink's default web server.
+
+The endpoint lives in :mod:`trame_server.mcp.endpoint.core`: this only turns
+aiohttp requests into an :class:`~trame_server.mcp.endpoint.core.HTTPRequest`,
+and the :class:`~trame_server.mcp.endpoint.core.HTTPResponse` back into an
+aiohttp response, streamed when it is Server-Sent Events.
+"""
+
+from __future__ import annotations
+
+import contextlib
+import logging
+
+from aiohttp import web
+
+from trame_server.mcp.endpoint.core import HTTPRequest, MCPEndpoint
+
+logger = logging.getLogger("trame_server.mcp")
+
+__all__ = ["mount", "routes"]
+
+
+def _from_aiohttp(request, open_stream=None):
+ def disconnected():
+ transport = request.transport
+ return transport is None or transport.is_closing()
+
+ return HTTPRequest(
+ method=request.method,
+ headers={k.lower(): v for k, v in request.headers.items()},
+ authority=request.host,
+ read=request.read,
+ disconnected=disconnected,
+ open_stream=open_stream,
+ )
+
+
+def _to_aiohttp(response):
+ if response.body is None:
+ return web.Response(
+ status=response.status, headers=response.headers, reason=response.reason
+ )
+ return web.json_response(
+ response.body, status=response.status, headers=response.headers
+ )
+
+
+def routes(endpoint, path):
+ """The aiohttp routes serving ``endpoint`` (an :class:`MCPEndpoint`) at
+ ``path``."""
+
+ async def post(request):
+ streams = []
+
+ async def open_stream(headers):
+ stream = web.StreamResponse(status=200, headers=headers)
+ await stream.prepare(request)
+ streams.append(stream)
+
+ async def write(text):
+ await stream.write(text.encode())
+
+ return write
+
+ response = await endpoint.post(_from_aiohttp(request, open_stream))
+ if not response.streamed:
+ return _to_aiohttp(response)
+ (stream,) = streams
+ with contextlib.suppress(ConnectionError): # the client may be gone
+ await stream.write_eof()
+ return stream
+
+ async def other(_request):
+ return _to_aiohttp(endpoint.unsupported())
+
+ return [web.post(path, post), web.get(path, other), web.delete(path, other)]
+
+
+def mount(server, wslink_server):
+ """Mount the endpoint of ``server`` on the web server wslink started, when it is
+ aiohttp's, and return whether it did. The ``generic``, ``jupyter`` and
+ ``tornado`` backends give trame no web server to mount it on."""
+ app = getattr(wslink_server, "app", None)
+ mcp = server._mcp
+ if not isinstance(app, web.Application):
+ # Only worth mentioning to an app that uses agents
+ log = logger.info if mcp is not None else logger.debug
+ log(
+ "The MCP endpoint is not mounted: this web server is not aiohttp. "
+ "Agents in the process can use server.mcp.client(), and the host can "
+ "serve trame_server.mcp.endpoint.MCPEndpoint"
+ )
+ return False
+
+ path = mcp.http.path if mcp is not None else "/mcp"
+ app.add_routes(routes(MCPEndpoint(server), path))
+ return True
diff --git a/src/trame_server/mcp/endpoint/core.py b/src/trame_server/mcp/endpoint/core.py
new file mode 100644
index 0000000..0da9819
--- /dev/null
+++ b/src/trame_server/mcp/endpoint/core.py
@@ -0,0 +1,536 @@
+"""The HTTP endpoint agents connect to (``server.mcp.http``, ``/mcp`` by
+default), on the trame web server's port, independent of the web server.
+
+:class:`HTTPTransport` holds its options. :class:`MCPEndpoint` handles
+requests without depending on a web server: a host hands it an
+:class:`HTTPRequest` and sends back the :class:`HTTPResponse`.
+:mod:`trame_server.mcp.endpoint.aiohttp` serves it on aiohttp, trame's
+default web server. The server mounts it when it starts, unless the launch
+options keep it off for the whole run (no ``--mcp``, or ``--mcp-transport
+none``, without ``--mcp-mutable``). The route exists from the start because
+aiohttp freezes its routes then, while agent access and the transport can
+be turned on later. Until ``server.mcp`` exists, is enabled and serves
+HTTP, the endpoint answers 503.
+
+Every request goes through, in order:
+
+1. ``Origin`` check: browsers always send it on cross-site requests, so a
+ page from another site can never drive the tools (CSRF).
+2. The key (``mcp.http.secret``), as a bearer token. One is always required,
+ even when the server listens on loopback only: other users of the machine,
+ and reverse proxies, reach loopback too. A page that rebinds its domain to
+ 127.0.0.1 doesn't know it either. Until ``server.mcp`` exists there is no
+ key, and nothing to serve: 503.
+3. ``mcp.enabled``, then ``"http"`` in ``mcp.transports``: 503 while
+ agent access or the transport is off.
+4. ``Content-Type: application/json``, so browsers cannot send a request
+ without a CORS preflight, which this endpoint never grants.
+
+The transport is streamable HTTP with JSON responses, for clients of both
+eras (see :mod:`trame_server.mcp.protocol`):
+
+- A request naming its protocol version in ``_meta`` (2026-07-28 and
+ later) is served statelessly. Its ``MCP-Protocol-Version``,
+ ``Mcp-Method`` and ``Mcp-Name`` headers must match its body, else 400
+ (``HeaderMismatch``). An unsupported version or missing metadata gets
+ 400, and an unknown method 404. No session id is given or read.
+- A client that opens with ``initialize`` is served as earlier revisions
+ say: the response carries an ``Mcp-Session-Id`` that only scopes request
+ ids for ``notifications/cancelled``.
+
+Either way, a request whose client disconnects is cancelled. A request
+that asks for progress gets its response as Server-Sent Events once its
+first notification goes out: the notifications, then the response.
+Without a notification, the response stays plain JSON.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import base64
+import ipaddress
+import json
+import logging
+import secrets
+import shlex
+from collections.abc import Awaitable, Callable, Mapping
+from dataclasses import dataclass, field
+from urllib.parse import urlsplit
+
+from trame_server import auth
+from trame_server.mcp.protocol import (
+ HEADER_MISMATCH,
+ INVALID_REQUEST,
+ METHOD_NOT_FOUND,
+ MODERN_VERSIONS,
+ PARSE_ERROR,
+ check_request,
+ request_version,
+)
+from trame_server.utils.server import http_scheme
+
+logger = logging.getLogger("trame_server.mcp")
+
+__all__ = [
+ "HTTPRequest",
+ "HTTPResponse",
+ "HTTPTransport",
+ "MCPEndpoint",
+ "claude_command",
+ "codex_command",
+ "is_loopback",
+]
+
+WILDCARD_HOSTS = ("", "0.0.0.0", "::")
+SERVER_ERROR = -32000
+DISABLED_MESSAGE = "MCP access is currently disabled by the application"
+SESSION_HEADER = "Mcp-Session-Id"
+# Seconds between checks that the client of a running request is still there
+DISCONNECT_POLL = 0.5
+# The body field each method mirrors into Mcp-Name (2026-07-28)
+NAMED_BY = {"tools/call": "name", "prompts/get": "name", "resources/read": "uri"}
+# How a header value outside plain ASCII is sent (2026-07-28)
+BASE64_PREFIX, BASE64_SUFFIX = "=?base64?", "?="
+# A response sent as Server-Sent Events (X-Accel-Buffering: proxies pass
+# each event on at once)
+EVENT_STREAM_HEADERS = {
+ "Content-Type": "text/event-stream",
+ "Cache-Control": "no-cache",
+ "X-Accel-Buffering": "no",
+}
+
+
+def is_loopback(host) -> bool:
+ """True for ``localhost`` names and loopback IP literals."""
+ if not host:
+ return False
+ host = host.strip("[]").lower()
+ if host == "localhost" or host.endswith(".localhost"):
+ return True
+ try:
+ return ipaddress.ip_address(host).is_loopback
+ except ValueError:
+ return False
+
+
+def claude_command(name, url, secret=None):
+ """A Claude Code command starting a session with this server added for
+ that session only (``--mcp-config``), next to the user's own MCP
+ servers. ``secret`` is the key, sent as a bearer token."""
+ server = {"type": "http", "url": url}
+ if secret:
+ server["headers"] = {"Authorization": f"Bearer {secret}"}
+ config = json.dumps({"mcpServers": {name: server}}, separators=(",", ":"))
+ return f"claude --mcp-config {shlex.quote(config)}"
+
+
+def codex_command(name, url, secret=None):
+ """A Codex command starting a session with this server added for that
+ session only: each ``-c`` overrides one config value (TOML) for the
+ run, here the server's entry under ``mcp_servers``. ``secret`` is the
+ key, sent as a bearer token."""
+ overrides = [f"mcp_servers.{name}.url={json.dumps(url)}"]
+ if secret:
+ header = json.dumps(f"Bearer {secret}")
+ overrides.append(f"mcp_servers.{name}.http_headers={{Authorization={header}}}")
+ return " ".join(["codex", *(f"-c {shlex.quote(o)}" for o in overrides)])
+
+
+class HTTPTransport:
+ """The options of the HTTP transport (``server.mcp.http``), which is served
+ while ``mcp.transports`` includes ``"http"``, as it does by default.
+
+ Every option is a settable attribute, and ``configure()`` sets several at
+ once. ``path`` is fixed once the server has started; the other options
+ can change at any time.
+ """
+
+ def __init__(self, mcp):
+ self._mcp = mcp
+ self._path = "/mcp"
+ self._secret = None
+ self._secret_generated = False
+ self._allowed_origins = ()
+ self._announced = False
+
+ def configure(self, *, path=None, secret=None, allowed_origins=None):
+ """Set several options at once; an option left as None is unchanged. This
+ is the same as assigning the attributes one by one."""
+ options = {"path": path, "secret": secret, "allowed_origins": allowed_origins}
+ for key, value in options.items():
+ if value is not None:
+ setattr(self, key, value)
+
+ @property
+ def path(self):
+ """The endpoint's path on the trame web server. It is fixed once the server
+ has started."""
+ return self._path
+
+ @path.setter
+ def path(self, value):
+ if self._mcp._shared.started:
+ msg = "MCP 'path' cannot change once the server has started"
+ raise RuntimeError(msg)
+ self._path = value if value.startswith("/") else f"/{value}"
+
+ @property
+ def secret(self):
+ """The key agents in other processes must send, as a bearer token. It is
+ always required: when none is set, the server generates one as it starts,
+ and prints it with the connection commands.
+
+ ``--mcp-auth-key-file``, ``--mcp-auth-key`` and their environment variables
+ set it for the whole run: the application's values are then ignored.
+ Otherwise, setting None or an empty value generates a key: at start, or
+ at once if the server has started.
+ """
+ return self._secret
+
+ @secret.setter
+ def secret(self, value):
+ if self._mcp._launch_holds("secret"):
+ return
+ self._secret = str(value) if value else None
+ self._secret_generated = False
+ if self._secret is None and self._mcp._shared.started:
+ self._generate_secret()
+
+ @property
+ def allowed_origins(self):
+ """Extra browser origins (``"https://host:port"``) allowed to call the
+ endpoint. Loopback origins and the endpoint's own origin are always
+ allowed; requests without an ``Origin`` header are unaffected."""
+ return self._allowed_origins
+
+ @allowed_origins.setter
+ def allowed_origins(self, value):
+ if isinstance(value, str):
+ value = (value,)
+ self._allowed_origins = tuple(o.rstrip("/") for o in value)
+
+ @property
+ def url(self):
+ """The endpoint's URL, as agents on this machine reach it.
+
+ The scheme follows the web server: ``https`` when launched with
+ ``--ssl``. Agents must trust its certificate, so the self-signed one
+ from ``--ssl adhoc`` won't do for Claude Code or Codex: use
+ ``--ssl cert,key`` with a certificate they trust.
+ """
+ host = self._bind_host
+ if not host or host in WILDCARD_HOSTS:
+ host = "localhost"
+ elif ":" in host:
+ host = f"[{host}]"
+ scheme = http_scheme(self._mcp.server.server_options)
+ return f"{scheme}://{host}:{self._mcp.server.port}{self._path}"
+
+ @property
+ def _bind_host(self):
+ return getattr(self._mcp.server.server_options, "host", None)
+
+ @property
+ def _mounted(self):
+ return self._mcp.server._mcp_endpoint_mounted
+
+ @property
+ def _serving(self):
+ return self._mounted and "http" in self._mcp.transports
+
+ @property
+ def _live(self):
+ return self._mcp.enabled and self._serving
+
+ def _start(self):
+ if self._secret is None:
+ self._generate_secret()
+
+ def _generate_secret(self):
+ self._secret = auth.resolve_secret(auth.AUTO_SECRET)
+ self._secret_generated = True
+
+ def _on_ready(self):
+ if self._live:
+ self._announce()
+ elif not self._mcp.enabled and self._mounted:
+ logger.info(
+ "%s is mounted, but agent access is off (set mcp.enabled = True or "
+ "launch with --mcp)",
+ self.url,
+ )
+ elif self._mounted:
+ logger.info(
+ "%s is mounted, but the HTTP transport is off (add it to "
+ "mcp.transports)",
+ self.url,
+ )
+
+ def _announce(self):
+ """Print how to connect, the first time access is live."""
+ if self._announced or not (self._mcp._shared.ready and self._live):
+ return
+ self._announced = True
+ from trame_server.utils.server import print_mcp_informations # noqa: PLC0415
+
+ print_mcp_informations(self._mcp)
+
+
+@dataclass
+class HTTPRequest:
+ """What the endpoint needs of a request."""
+
+ method: str
+ headers: Mapping[str, str] # lower-case names
+ authority: str | None # the ``Host`` header as sent: host[:port]
+ read: Callable[[], Awaitable[bytes]]
+ disconnected: Callable[[], bool] = lambda: False
+ # Starts the response as a stream with these headers; returns an async
+ # function writing text to it. None: the host can't stream responses.
+ open_stream: (
+ Callable[[dict], Awaitable[Callable[[str], Awaitable[None]]]] | None
+ ) = None
+
+ @property
+ def content_type(self):
+ value = self.headers.get("content-type") or ""
+ return value.split(";")[0].strip().lower()
+
+
+@dataclass
+class HTTPResponse:
+ status: int
+ body: dict | None = None
+ headers: dict = field(default_factory=dict)
+ reason: str | None = None
+ streamed: bool = False # sent already, on the stream ``open_stream`` began
+
+
+class _EventStream:
+ """A request's response as Server-Sent Events, begun by the first
+ notification: the notifications, then the response."""
+
+ def __init__(self, request):
+ self._request = request
+ self._write = None
+
+ @property
+ def begun(self):
+ return self._write is not None
+
+ async def send(self, message):
+ if self._write is None:
+ self._write = await self._request.open_stream(EVENT_STREAM_HEADERS)
+ data = json.dumps(message, separators=(",", ":"))
+ await self._write(f"event: message\ndata: {data}\n\n")
+
+
+def _event_stream(request):
+ """The event stream that a request's first notification starts, or None when
+ its host or its client cannot use one."""
+ accept = request.headers.get("accept") or ""
+ if request.open_stream is None or "text/event-stream" not in accept:
+ return None
+ return _EventStream(request)
+
+
+def _error_response(status, message, headers=None, code=SERVER_ERROR, rpc_id=None):
+ body = {"jsonrpc": "2.0", "id": rpc_id, "error": {"code": code, "message": message}}
+ return HTTPResponse(status, body, headers or {})
+
+
+def _decoded(value):
+ """A header value, decoded when sent in the Base64 form."""
+ if value.startswith(BASE64_PREFIX) and value.endswith(BASE64_SUFFIX):
+ encoded = value[len(BASE64_PREFIX) : -len(BASE64_SUFFIX)]
+ try:
+ return base64.b64decode(encoded, validate=True).decode("utf-8")
+ except ValueError: # binascii.Error, UnicodeDecodeError
+ return None
+ return value
+
+
+def _header_mismatch(headers, message):
+ """What is wrong with the headers a 2026-07-28 request mirrors from its
+ body, or None."""
+ method = message.get("method")
+ params = message.get("params")
+ params = params if isinstance(params, dict) else {}
+ expected = [
+ ("MCP-Protocol-Version", request_version(message)),
+ ("Mcp-Method", method),
+ ]
+ if method in NAMED_BY:
+ expected.append(("Mcp-Name", params.get(NAMED_BY[method])))
+ for name, value in expected:
+ sent = headers.get(name.lower())
+ if sent is None:
+ return f"Header mismatch: the {name} header is missing"
+ if name == "Mcp-Name":
+ sent = _decoded(sent)
+ if sent != value:
+ return (
+ f"Header mismatch: {name} header value {sent!r} does not match "
+ f"body value {value!r}"
+ )
+ return None
+
+
+async def _cancel_on_disconnect(request, task):
+ """Cancel ``task`` if the client of ``request`` disconnects before it ends, and
+ return whether it did. aiohttp keeps a handler running after its client is
+ gone, and exposes no callback for it once the body is read."""
+ while not task.done():
+ await asyncio.sleep(DISCONNECT_POLL)
+ if request.disconnected():
+ task.cancel()
+ return True
+ return False
+
+
+class MCPEndpoint:
+ """Serves MCP over HTTP for a trame server (its root), whether or not
+ ``server.mcp`` exists yet."""
+
+ def __init__(self, server):
+ self._server = server.root_server
+
+ @property
+ def _mcp(self):
+ return self._server._mcp
+
+ def _origin_allowed(self, origin, request):
+ mcp = self._mcp
+ if mcp is not None and origin in mcp.http.allowed_origins:
+ return True
+ try:
+ parsed = urlsplit(origin)
+ except ValueError:
+ return False
+ if not parsed.hostname: # e.g. "null" from sandboxed frames / file://
+ return False
+ return is_loopback(parsed.hostname) or parsed.netloc == request.authority
+
+ def _check(self, request):
+ origin = request.headers.get("origin")
+ if origin is not None and not self._origin_allowed(origin, request):
+ logger.warning("Rejected an MCP request from origin %r", origin)
+ return _error_response(403, "Origin not allowed")
+
+ mcp = self._mcp
+ if mcp is None:
+ return _error_response(503, DISABLED_MESSAGE)
+ if not auth.check_secret(mcp.http.secret, _bearer(request)):
+ return _error_response(
+ 401, "Unauthorized", headers={"WWW-Authenticate": "Bearer"}
+ )
+
+ if not mcp.enabled:
+ return _error_response(503, DISABLED_MESSAGE)
+ if "http" not in mcp.transports:
+ return _error_response(503, "The application turned its HTTP transport off")
+
+ if request.content_type != "application/json":
+ return _error_response(415, "Content-Type must be application/json")
+
+ return None
+
+ def _check_modern(self, request, message):
+ """The 400 or 404 response that a request from a 2026-07-28 client gets, or
+ None. Such a request names its version in its body, or its headers say it
+ should."""
+ if (
+ request_version(message) is None
+ and request.headers.get("mcp-protocol-version") not in MODERN_VERSIONS
+ ):
+ return None
+ rpc_id = message.get("id")
+ mismatch = _header_mismatch(request.headers, message)
+ if mismatch is not None:
+ return _error_response(400, mismatch, code=HEADER_MISMATCH, rpc_id=rpc_id)
+ error = check_request(message)
+ if error is not None:
+ return HTTPResponse(400, error)
+ if not self._mcp.protocol.handles(message):
+ return _error_response(
+ 404,
+ f"Method not found: {message.get('method')}",
+ code=METHOD_NOT_FOUND,
+ rpc_id=rpc_id,
+ )
+ return None
+
+ async def post(self, request: HTTPRequest) -> HTTPResponse:
+ rejection = self._check(request)
+ if rejection is not None:
+ return rejection
+
+ try:
+ message = json.loads(await request.read())
+ except (json.JSONDecodeError, UnicodeDecodeError):
+ return _error_response(400, "Parse error", code=PARSE_ERROR)
+
+ if isinstance(message, list):
+ return _error_response(
+ 400, "JSON-RPC batching is not supported", code=INVALID_REQUEST
+ )
+
+ protocol = self._mcp.protocol
+ is_request = (
+ isinstance(message, dict) and "method" in message and "id" in message
+ )
+ session = None
+ if is_request and (rejection := self._check_modern(request, message)):
+ return rejection
+ if not isinstance(message, dict) or request_version(message) is None:
+ # Before 2026-07-28 only: a session scoping cancellation
+ session = request.headers.get(SESSION_HEADER.lower())
+ stream = _event_stream(request) if is_request else None
+ if is_request:
+ notify = stream.send if stream is not None else None
+ handling = asyncio.ensure_future(
+ protocol.handle(message, session=session, notify=notify)
+ )
+ watching = asyncio.ensure_future(_cancel_on_disconnect(request, handling))
+ try:
+ response = await handling
+ except asyncio.CancelledError:
+ if not (
+ watching.done() and not watching.cancelled() and watching.result()
+ ):
+ raise
+ logger.info(
+ "MCP client disconnected, cancelled %s request %r",
+ message.get("method"),
+ message.get("id"),
+ )
+ # Never delivered; for the access log, as nginx does
+ begun = stream is not None and stream.begun
+ return HTTPResponse(499, reason="Client Closed Request", streamed=begun)
+ finally:
+ watching.cancel()
+ else:
+ response = await protocol.handle(message, session=session)
+ if response is None:
+ # Notification or client response: acknowledge without a body
+ return HTTPResponse(202)
+ if stream is not None and stream.begun:
+ await stream.send(response)
+ return HTTPResponse(200, streamed=True)
+
+ headers = {}
+ if is_request and message["method"] == "initialize" and "result" in response:
+ headers[SESSION_HEADER] = secrets.token_urlsafe(24)
+ return HTTPResponse(200, response, headers)
+
+ @staticmethod
+ def unsupported(_request=None) -> HTTPResponse:
+ # Stateless server: no SSE stream to offer (GET), no session to end (DELETE)
+ return HTTPResponse(405, headers={"Allow": "POST"})
+
+
+def _bearer(request):
+ """The credentials of the request's ``Authorization: Bearer ...`` header, or
+ None."""
+ scheme, _, credentials = request.headers.get("authorization", "").partition(" ")
+ return credentials.strip() if scheme.lower() == "bearer" else None
diff --git a/src/trame_server/mcp/objects.py b/src/trame_server/mcp/objects.py
new file mode 100644
index 0000000..7920ae4
--- /dev/null
+++ b/src/trame_server/mcp/objects.py
@@ -0,0 +1,1833 @@
+"""The objects agents reach, and the six tools that work on them.
+
+Objects are:
+
+- instances of ``MCPExposable`` classes, such as components
+ (``TrameComponent``) and trame-dataclass models, whose class declares
+ something. Agents reach them by the names the application
+ gives them, or by id through the visible properties of an object they
+ already reach;
+- the ``state`` object, whose properties are the state keys the
+ application exposes (``state.mcp_expose()``).
+
+``object_list``, ``object_types``, ``object_get``, ``object_update``,
+``object_call`` and ``object_batch`` serve all objects, so the tool list
+never changes as objects come and go.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import inspect
+import json
+import logging
+import re
+import weakref
+from dataclasses import dataclass, field
+from typing import Annotated, Literal
+
+from trame_server.mcp import budget, progress, typeinfo
+from trame_server.mcp.permissions import PermissionDeniedError
+from trame_server.mcp.schema import (
+ ToolError,
+ ValidationError,
+ bind_arguments,
+ error_text,
+ from_json,
+ function_input_schema,
+ is_object,
+ object_classes,
+ resolve_object_arguments,
+ return_hint,
+ type_to_schema,
+ validate,
+)
+from trame_server.mcp.typeinfo import (
+ STATE_TYPE,
+ Property,
+ TypeInfo,
+ is_visible,
+ property_schema,
+ reference_schema,
+ subclasses,
+ type_info,
+ type_name,
+)
+
+logger = logging.getLogger("trame_server.mcp")
+
+__all__ = ["OBJECT_TOOLS", "BatchError", "NotFoundError", "ObjectLayer", "StateObject"]
+
+OBJECT_TOOLS = (
+ "object_list",
+ "object_types",
+ "object_get",
+ "object_update",
+ "object_call",
+ "object_batch",
+)
+STATE_NAME = "state"
+NAME = re.compile(r"^[A-Za-z_]")
+MAX_DEPTH = 10
+# Objects the connection instructions name
+MAX_LISTED = 20
+# The object tools' parameters, as their input schemas say
+Target = Annotated[str, "Object name or id"]
+Depth = Annotated[int, {"minimum": 1, "maximum": MAX_DEPTH}]
+Offset = Annotated[int, {"minimum": 0}]
+TypeNames = Annotated[
+ list[str] | None,
+ 'Types ("Viewer") or members ("Viewer.reset")',
+]
+
+LIST_DESCRIPTION = """\
+List the objects this app names, as {"objects": {name: {"type", "read_only"?, \
+"description"?}}}. "description" says what the object is for; "type" is null \
+while the name holds nothing. The objects they refer to are reached by id, as \
+object_get shows them. When "more" is present, it gives the call that lists \
+the next ones."""
+
+TYPES_DESCRIPTION = """\
+Describe the types of this app's objects. Without `type_names`, it returns an \
+index of the types; with them, types in full ("Viewer") or single members \
+("Viewer.set_view_up"). A subclass lists what it adds, under "extends", unless \
+`include_inherited`; false marks what it lacks. \
+{"object": "T"} is a value holding an object of type T: read as a reference, \
+returned by a method as object_get shows it, written by its id."""
+
+GET_DESCRIPTION = """\
+Read an object. `target` is an object name or id. \
+The reply is {"result", "objects"}: "result" refers to what was read, and \
+"objects" holds each object read, by id, once, as {"type", "values"}. A \
+reference is {"id"}, and {"id", "type"} for an object not read here. `depth` \
+reads objects up to that many references away. `properties` reads only those, \
+in full. What is cut short is listed under "more", with the call that reads \
+the rest."""
+
+UPDATE_DESCRIPTION = """\
+Write properties of an object: `values` maps property names to values \
+(objects by id), as object_get reads them. Every value is checked before any \
+is applied."""
+
+CALL_DESCRIPTION = """\
+Call a method of an object. `args` maps parameter names to values (objects by \
+id or name). A result holding objects comes back as object_get shows it."""
+
+BATCH_DESCRIPTION = """\
+Run steps in order, in one call: {"new": "", "args", "as"} builds an \
+object; {"call": target, "method", "args", "as"}; {"update": target, "values"}. \
+"@name" is the result of the step named so ("@name.prop.0" follows properties \
+and indexes, "@@" is a literal "@"). Steps are checked before any runs; the \
+first failure stops the batch and earlier steps stay applied. An object built \
+and never attached is dropped, listed in "unattached". Objects are read as \
+object_get does; with `results` "links", only their references to others."""
+
+_STEP_KEYS = {
+ "new": ("new", "args", "as"),
+ "call": ("call", "method", "args", "as"),
+ "update": ("update", "values"),
+}
+_STEP_NAME = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")
+
+_HIDDEN = object()
+
+
+async def _settle(obj):
+ """Wait for the work a change started, such as the watchers trame-dataclass runs
+ in a task. Without this, the reply and the agent's next read would not reflect
+ what that work derives."""
+ if not is_object(obj):
+ return
+ try:
+ await obj._mcp_settle()
+ except Exception:
+ # The change itself is applied: a failing watcher is the app's bug,
+ # not the agent's, and must not read as "nothing was applied".
+ logger.exception("A watcher of %s %s raised", type(obj).__name__, obj._id)
+
+
+# -----------------------------------------------------------------------------
+# The state object
+# -----------------------------------------------------------------------------
+
+
+class StateObject:
+ """The ``state`` object: its properties are the trame state keys the app
+ exposed (``server.state.mcp_expose()``), with their real names (a child
+ server's prefix included)."""
+
+ _id = STATE_NAME
+
+ def __init__(self):
+ self._keys = {} # key -> Property
+ self._info = None
+
+ def __bool__(self):
+ return bool(self._keys)
+
+ def expose(self, key, *, type=None, schema=None, description=None, read_only=False):
+ if not isinstance(read_only, bool):
+ msg = "read_only must be True or False"
+ raise TypeError(msg)
+ var_schema, description = property_schema(
+ type, {"schema": schema, "description": description}
+ )
+ self._keys[key] = Property(
+ name=key,
+ origin="state",
+ schema=var_schema,
+ description=description,
+ writable=not read_only,
+ type_def=type,
+ )
+ self._info = None
+
+ def unexpose(self, *keys):
+ for key in keys:
+ self._keys.pop(key, None)
+ self._info = None
+
+ @property
+ def info(self) -> TypeInfo:
+ if self._info is None:
+ self._info = TypeInfo(cls=None, visible=True, properties=dict(self._keys))
+ return self._info
+
+
+# -----------------------------------------------------------------------------
+# Exposure
+# -----------------------------------------------------------------------------
+
+
+# How an exposed name holds what it was given (_Entry.source_type)
+SourceType = Literal[
+ "strong", # the object itself, held strongly
+ "weak", # the object, held weakly: the name doesn't keep it alive
+ "getter", # a function returning the object or None, called on every request
+]
+
+
+class _Entry:
+ """What a name exposes, and how it holds it (``source_type``):
+
+ - ``"strong"``: the object itself, held strongly, as models are.
+ - ``"weak"``: the object through a weak reference, for classes whose
+ instances something else keeps alive while in use (``_mcp_hold_weakly``),
+ as components are by the callbacks they bind. The name is :meth:`gone`
+ once the object is collected.
+ - ``"getter"``: a function returning the object, or None, called again on
+ every request, so that ``lambda: self.active`` follows reassignment.
+
+ :meth:`ObjectLayer.expose` picks the type. ``"weak"`` falls back to
+ ``"strong"`` for an instance that can't be referenced weakly.
+ """
+
+ __slots__ = ("_value", "description", "read_only", "source_type")
+
+ def __init__(self, source_type: SourceType, value, description, read_only):
+ self.source_type = source_type
+ self.description = description
+ self.read_only = bool(read_only)
+ if source_type == "weak":
+ try:
+ value = weakref.ref(value)
+ except TypeError: # no __weakref__: held
+ self.source_type = "strong"
+ self._value = value
+
+ def resolve(self):
+ if self.source_type in ("weak", "getter"):
+ return self._value()
+ return self._value
+
+ def holds(self, obj):
+ """Whether this entry names ``obj`` itself."""
+ return self.source_type in ("weak", "strong") and self.resolve() is obj
+
+ def exposes(self, source):
+ """Whether ``source`` is what this entry was given."""
+ if self.source_type == "getter":
+ return self._value == source # bound methods are rebuilt on access
+ return self.resolve() is source
+
+ def gone(self):
+ """Whether the object this entry held weakly was garbage collected."""
+ return self.source_type == "weak" and self._value() is None
+
+
+@dataclass
+class Graph:
+ """What agents reach now.
+
+ ``objects`` maps ids to ``(object, writable)``; ``entries`` maps names
+ to ``(value, read_only)``; ``names`` maps ids to the names exposing them.
+ """
+
+ objects: dict
+ entries: dict
+ names: dict = field(default_factory=dict)
+
+
+@dataclass
+class _Read:
+ """An object read for a reply, with its raw property values."""
+
+ obj: object
+ writable: bool
+ distance: int # references away from what was read
+ raw: dict
+ errors: dict
+
+
+class _Scope:
+ """What one ``object_batch`` holds: the results named with ``as``, and
+ the models its ``new`` steps built (held until it ends)."""
+
+ def __init__(self):
+ self.names = {}
+ self.built = {} # _id -> model
+
+
+class NotFoundError(ToolError, LookupError):
+ """An object, type, member or property the agent named does not exist. The
+ message lists what does exist."""
+
+
+class BatchError(ToolError):
+ """An ``object_batch`` step failed. The message says which one, why, and what the
+ steps before it returned."""
+
+
+class ObjectLayer:
+ """The objects of one MCP server and the object tools."""
+
+ def __init__(self, mcp):
+ self._mcp = mcp
+ self._entries = {} # name -> _Entry
+ self.state = StateObject()
+ self._registered = False
+ self._warned = weakref.WeakSet() # classes warned about
+
+ # -------------------------------------------------------------------------
+ # Exposure (server.mcp)
+ # -------------------------------------------------------------------------
+
+ def remove(self, obj):
+ """Withdraw every name exposing ``obj``."""
+ for name in [n for n, e in self._entries.items() if e.holds(obj)]:
+ del self._entries[name]
+
+ def expose(self, source, name, description=None, read_only=False):
+ if not isinstance(name, str) or not NAME.match(name):
+ msg = f"An object name starts with a letter or an underscore, got {name!r}"
+ raise ValueError(msg)
+ if name == STATE_NAME:
+ msg = (
+ f"{STATE_NAME!r} is reserved for the state object "
+ f"(server.state.mcp_expose())"
+ )
+ raise ValueError(msg)
+ if description is not None and not isinstance(description, str):
+ msg = f"description must be a string, got {type(description).__name__}"
+ raise TypeError(msg)
+
+ if is_object(source):
+ if not is_visible(type(source)):
+ cls = type(source).__name__
+ msg = (
+ f"{cls} declares nothing for agents: mark its members with "
+ f"@mcp.method / @mcp.property, or use the mcp= class keyword "
+ f"(or {cls}.mcp_describe() for a class you don't own)"
+ )
+ raise TypeError(msg)
+ source_type = "weak" if type(source)._mcp_hold_weakly else "strong"
+ elif callable(source) and not isinstance(source, type):
+ source_type = "getter"
+ else:
+ msg = (
+ "expose_object() takes a component, a model, or a function "
+ f"returning one; got {type(source).__name__}. Expose the items "
+ f"of a list each under its own name, or through a property of "
+ f"an object."
+ )
+ raise TypeError(msg)
+
+ current = self._entries.get(name)
+ if current is not None and not current.gone() and not current.exposes(source):
+ if current.source_type == "getter":
+ held = "a function"
+ else:
+ held = self._label(current.resolve())
+ msg = (
+ f"{name!r} already exposes {held}; withdraw it first "
+ f"(server.mcp.unexpose_object({name!r}))"
+ )
+ raise ValueError(msg)
+ self._entries[name] = _Entry(source_type, source, description, read_only)
+ self._ensure_tools()
+
+ def unexpose(self, name):
+ if self._entries.pop(name, None) is None:
+ msg = f"No object is exposed as {name!r}"
+ raise KeyError(msg)
+
+ def expose_state(self, key, **options):
+ self.state.expose(key, **options)
+ self._ensure_tools()
+
+ def exposes_anything(self):
+ return bool(self._entries or self.state)
+
+ # -------------------------------------------------------------------------
+ # Reachability
+ # -------------------------------------------------------------------------
+
+ def _is_object(self, value):
+ return is_object(value) and is_visible(type(value))
+
+ def _info(self, obj) -> TypeInfo:
+ if obj is self.state:
+ return self.state.info
+ return type_info(type(obj))
+
+ def _type(self, obj) -> str:
+ if obj is self.state:
+ return STATE_TYPE
+ return type_name(type(obj))
+
+ def _label(self, obj) -> str:
+ if obj is self.state:
+ return STATE_NAME
+ return f"{self._type(obj)} {obj._id}"
+
+ def _read(self, obj, prop):
+ if prop.origin == "state":
+ return self._mcp.server.state[prop.name]
+ return getattr(obj, prop.name)
+
+ def _readable(self, info):
+ """``{name: Property}`` of the properties agents may read now: those
+ whose permissions are on."""
+ permissions = self._mcp.permissions
+ return {
+ name: prop
+ for name, prop in info.properties.items()
+ if permissions.allows(prop.requires)
+ }
+
+ def _children(self, obj):
+ for prop in self._readable(self._info(obj)).values():
+ if not prop.reference:
+ continue
+ try:
+ value = self._read(obj, prop)
+ except Exception:
+ logger.debug("Reading %s.%s raised", self._type(obj), prop.name)
+ continue
+ yield from _objects_within(value, self._is_object)
+
+ def _graph(self, scope=None) -> Graph:
+ """Everything agents reach now: what names expose, and the objects
+ visible properties refer to from there. An object is writable when a
+ writable path reaches it."""
+ entries = {}
+ for name, entry in list(self._entries.items()):
+ try:
+ value = entry.resolve()
+ except Exception:
+ logger.exception("Resolving the object exposed as %r raised", name)
+ value = None
+ if value is not None and not self._is_object(value):
+ logger.warning(
+ "%r exposes a %s, not a component or model agents can see",
+ name,
+ type(value).__name__,
+ )
+ value = None
+ entries[name] = (value, entry.read_only)
+
+ names = {} # id -> the names exposing it
+ roots = []
+ for name, (value, read_only) in entries.items():
+ if value is not None:
+ names.setdefault(value._id, []).append(name)
+ roots.append((value, not read_only))
+ if scope is not None:
+ roots.extend((obj, True) for obj in scope.built.values())
+
+ objects = {}
+ for writable in (True, False):
+ stack = [obj for obj, w in roots if w is writable]
+ while stack:
+ obj = stack.pop()
+ if obj._id in objects:
+ continue
+ objects[obj._id] = (obj, writable)
+ stack.extend(self._children(obj))
+ if self.state:
+ objects[STATE_NAME] = (self.state, True)
+
+ return Graph(objects=objects, entries=entries, names=names)
+
+ def _unknown(self, target, graph):
+ names = [*graph.entries, *([STATE_NAME] if self.state else [])]
+ if not names:
+ return (
+ f"Unknown object {json.dumps(target)}: no object has that name or "
+ f"id; object_list() lists the objects."
+ )
+ return (
+ f"Unknown object {json.dumps(target)}. Objects: {', '.join(names)} "
+ f"(or an object id); object_list() lists them all."
+ )
+
+ def _object(self, target, graph):
+ """``(object, writable)`` for a target name or id."""
+ if not isinstance(target, str) or not target:
+ msg = "`target` must be an object name or id"
+ raise ValidationError(msg)
+ if target in graph.entries:
+ value, _ = graph.entries[target]
+ if value is None:
+ msg = f"The object exposed as {json.dumps(target)} is currently empty"
+ raise NotFoundError(msg)
+ found = graph.objects.get(value._id)
+ if found is not None:
+ return found
+ found = graph.objects.get(target)
+ if found is not None:
+ return found
+ raise NotFoundError(self._unknown(target, graph))
+
+ def _resolver(self, scope, read_only):
+ """``resolve(value, cls, path)`` for object-typed parameters and
+ properties: an id or name of a reachable object of class ``cls``."""
+ graph = None
+
+ def resolve(value, cls, path):
+ nonlocal graph
+ if graph is None:
+ graph = self._graph(scope)
+ found = graph.objects.get(value)
+ if found is None and value in graph.entries:
+ named = graph.entries[value][0]
+ if named is not None:
+ found = graph.objects.get(named._id)
+ expected = type_name(cls)
+ if found is None or found[0] is self.state:
+ msg = (
+ f"{path}: {json.dumps(value)} is not the id or name of an object "
+ f"agents can reach (an object of type {expected} is expected)"
+ )
+ raise ValidationError(msg)
+ obj, writable = found
+ if not isinstance(obj, cls):
+ msg = (
+ f"{path}: {json.dumps(value)} has type {self._type(obj)}, "
+ f"not {expected}"
+ )
+ raise ValidationError(msg)
+ if not writable and not read_only:
+ msg = (
+ f"{path}: {self._label(obj)} is exposed read-only; only read-only "
+ f"methods can take it"
+ )
+ raise PermissionError(msg)
+ return obj
+
+ return resolve
+
+ def resolve_arguments(
+ self, fn, arguments, *, read_only=False, scope=None, label="arguments"
+ ):
+ """``arguments`` of ``fn``, with the ids or names given for its object-typed
+ parameters replaced by the objects. An object must be reachable (or built
+ by the batch ``scope``) and of the annotated class, and one reached only
+ read-only can be passed to ``read_only`` callables only."""
+ return resolve_object_arguments(
+ fn, arguments, self._resolver(scope, read_only), label
+ )
+
+ # -------------------------------------------------------------------------
+ # Replies: what was read, with its objects as references, and the
+ # objects read, once each, in a flat table
+ # -------------------------------------------------------------------------
+
+ def _reply(
+ self,
+ value,
+ graph,
+ depth=1,
+ *,
+ target=None,
+ writable=True,
+ properties=None,
+ links=False,
+ spread=False,
+ ):
+ """``{"result", "objects"?, "more"?}``: ``value`` with its objects as
+ references, and the objects within ``depth`` steps of it read into
+ ``objects``, by id, nearest first. A reference is ``{"id"}`` for an object
+ that is read, and ``{"id", "type"}`` for one that is not.
+
+ Over the budget, the farthest objects are left out first, since
+ object_get reads them again; ``value`` is cut last.
+
+ :param target: the name the agent used for ``value``, used in the calls
+ that notes suggest.
+ :param writable: whether ``value``, a target object, is writable.
+ :param properties: the only properties of ``value`` to read, which
+ come back whole.
+ :param links: read only the properties holding objects.
+ :param spread: ``value``, a dict, gives the reply's own fields in
+ place of ``result``.
+ """
+ reads = self._gather(value, graph, depth, writable, properties)
+ order = list(reads)
+ requested = set(properties or ())
+
+ def call_target(obj_id):
+ return target if target and reads[obj_id].obj is value else obj_id
+
+ def build(count):
+ read = set(order[:count])
+ more = {}
+ objects = {}
+ for obj_id in order[:count]:
+ entry, notes = self._entry(
+ reads[obj_id],
+ graph,
+ reads,
+ read,
+ (call_target(obj_id), depth),
+ links,
+ requested,
+ )
+ objects[obj_id] = entry
+ more.update(notes)
+ if count < len(order):
+ more["objects"] = (
+ f"{count} of {len(order)} objects read to fit the response "
+ f"budget; object_get(id) reads one"
+ )
+ result = self._encode(value, graph, reads, read)
+ reply = {"result": None if result is _HIDDEN else result}
+ if objects:
+ reply["objects"] = objects
+ if more:
+ reply["more"] = more
+ return reply
+
+ def finish(reply):
+ if spread:
+ return {**reply.pop("result"), **reply}
+ return reply
+
+ room = self._budget()
+ reply = build(len(order))
+ if budget.size(reply) <= room:
+ return finish(reply)
+ # Leave out the farthest objects: the most that fit. One object read
+ # for itself stays, and its values are cut instead.
+ single = bool(order) and reads[order[0]].obj is value
+ low, high = int(single), len(order) - 1
+ while low < high:
+ middle = (low + high + 1) // 2
+ if budget.size(build(middle)) <= room:
+ low = middle
+ else:
+ high = middle - 1
+ reply = build(low)
+ if budget.size(reply) <= room:
+ return finish(reply)
+ if single: # the object read alone is still too big
+ return self._fit_entry(
+ reply, reads[order[0]], requested, (call_target(order[0]), depth)
+ )
+ # Then the result, noted under the fields the agent sees
+ result = reply["result"] if spread else {"result": reply["result"]}
+ rest = budget.size({k: v for k, v in reply.items() if k != "result"})
+ result, cuts = budget.shrink(result, room - rest - 200)
+ reply["result"] = result if spread else result["result"]
+ more = reply.setdefault("more", {})
+ for key, note in cuts.items():
+ more[key] = f"{note} to fit the response budget"
+ return finish(reply)
+
+ def _gather(self, value, graph, depth, writable, properties):
+ """``{id: _Read}``: the objects ``value`` holds, when agents can see their type,
+ then those reachable within ``depth`` steps, nearest first."""
+ reads = {}
+ pending = []
+
+ def admit(obj, distance):
+ if obj._id in reads or distance >= depth:
+ return
+ found = graph.objects.get(obj._id)
+ if distance == 0: # what was read: the target, or a call's result
+ if obj is not self.state and not is_visible(type(obj)):
+ return
+ if obj is value:
+ obj_writable = writable
+ else:
+ obj_writable = found[1] if found and found[0] is obj else True
+ elif found is None or found[0] is not obj:
+ return
+ else:
+ obj_writable = found[1]
+ wanted = properties if obj is value else None
+ reads[obj._id] = self._read_object(obj, obj_writable, distance, wanted)
+ pending.append(obj._id)
+
+ def visit(raw, distance, capped):
+ # A capped value keeps only its first items (see _entry). The
+ # objects in the other items are not shown, so they are not read
+ limit = budget.MAX_ITEMS if capped else None
+ for obj in _objects_within(raw, obj_like, limit):
+ admit(obj, distance)
+
+ def obj_like(raw):
+ return raw is self.state or is_object(raw)
+
+ visit(value, 0, False)
+ requested = set(properties or ())
+ index = 0
+ while index < len(pending):
+ read = reads[pending[index]]
+ index += 1
+ for name, raw in read.raw.items():
+ whole = read.distance == 0 and name in requested
+ visit(raw, read.distance + 1, not whole)
+ return reads
+
+ def _read_object(self, obj, writable, distance, wanted=None):
+ raw, errors = {}, {}
+ for prop in self._readable(self._info(obj)).values():
+ if wanted is not None and prop.name not in wanted:
+ continue
+ try:
+ raw[prop.name] = self._read(obj, prop)
+ except Exception as e:
+ errors[prop.name] = error_text(e)
+ return _Read(obj, writable, distance, raw, errors)
+
+ def _encode(self, value, graph, reads, read):
+ """``value`` as JSON: objects as references, those agents cannot
+ reach left out (``_HIDDEN``)."""
+ if value is self.state or is_object(value):
+ if value._id in read:
+ return {"id": value._id}
+ found = graph.objects.get(value._id)
+ known = reads.get(value._id)
+ if (known is not None and known.obj is value) or (
+ found is not None and found[0] is value
+ ):
+ return {"id": value._id, "type": self._type(value)}
+ return _HIDDEN
+ if isinstance(value, (list, tuple, set, frozenset)):
+ items = [self._encode(v, graph, reads, read) for v in value]
+ items = [v for v in items if v is not _HIDDEN]
+ if isinstance(value, (set, frozenset)):
+ return sorted(items, key=str)
+ return items
+ if isinstance(value, dict):
+ items = {
+ str(k): self._encode(v, graph, reads, read) for k, v in value.items()
+ }
+ return {k: v for k, v in items.items() if v is not _HIDDEN}
+ if value is None or isinstance(value, (str, int, float, bool)):
+ return value
+ tolist = getattr(value, "tolist", None) # numpy and friends
+ if callable(tolist):
+ try:
+ return self._encode(tolist(), graph, reads, read)
+ except Exception:
+ pass
+ return str(value)
+
+ def _entry(self, found, graph, reads, read, call, links, requested):
+ """``(entry, more)``: an object read, as ``objects`` lists it, with its
+ values capped unless they were requested. ``call`` is ``(target,
+ depth)``, used in the calls that notes suggest."""
+ obj = found.obj
+ target, depth = call
+ values, more = {}, {}
+ for name, raw in found.raw.items():
+ rendered = self._encode(raw, graph, reads, read)
+ rendered = None if rendered is _HIDDEN else rendered
+ if links and not _holds_references(rendered):
+ continue
+ if found.distance or name not in requested:
+ rendered, note = budget.cap(rendered)
+ if note:
+ rest = self._get_call(target, name, depth - found.distance)
+ more[f"{obj._id}.{name}"] = f"{note}; {rest} for all"
+ values[name] = rendered
+ entry = {"type": self._type(obj)}
+ if graph.names.get(obj._id):
+ entry["names"] = graph.names[obj._id]
+ if values:
+ entry["values"] = values
+ if found.errors:
+ entry["errors"] = found.errors
+ if not found.writable:
+ entry["read_only"] = True
+ return entry, more
+
+ def encode_tool_result(self, value):
+ """An app tool's result, the way object_get shows it when it holds objects, and
+ as is otherwise."""
+ if not _holds_objects(value):
+ return value
+ return self._reply(value, self._graph())
+
+ def _encode_result(self, value, graph):
+ """A method's or constructor's result, the way object_get shows it when it holds
+ objects. Anything else is returned as is, cut to fit the budget."""
+ if _holds_objects(value):
+ reply = self._reply(value, graph)
+ if reply["result"] is None and not reply.get("objects"):
+ return None
+ return reply
+ return self._fit_result(value)
+
+ # -------------------------------------------------------------------------
+ # Response budget
+ # -------------------------------------------------------------------------
+
+ def _budget(self):
+ return self._mcp.max_response_tokens * budget.CHARS_PER_TOKEN
+
+ @staticmethod
+ def _get_call(target, name, depth=1):
+ call = f"object_get({json.dumps(target)}, properties=[{json.dumps(name)}]"
+ if depth > 1:
+ call += f", depth={depth}"
+ return f"{call})"
+
+ def _fit_entry(self, reply, found, requested, call):
+ """Cut the largest values of a reply that reads one object, until it fits. Notes
+ go in ``reply["more"]``, keyed ``id.property``, and their counts come from the
+ values ``found`` read, before they were capped."""
+ target, depth = call
+ obj_id = found.obj._id
+ entry = reply["objects"][obj_id]
+ values, more = entry.get("values", {}), reply.setdefault("more", {})
+ room = self._budget() - budget.size({**reply, "objects": {}})
+ room -= budget.size({obj_id: {**entry, "values": {}}})
+ if budget.size(values) > room:
+ totals = {
+ name: len(raw)
+ for name, raw in found.raw.items()
+ if isinstance(raw, (str, list, tuple, set, frozenset))
+ }
+ values, cuts = budget.shrink(values, room, totals)
+ for name, note in cuts.items():
+ if name in requested:
+ more[f"{obj_id}.{name}"] = f"{note} to fit the response budget"
+ else:
+ rest = self._get_call(target, name, depth)
+ more[f"{obj_id}.{name}"] = f"{note}; {rest} alone for more"
+ while values and budget.size(values) > room - budget.size(more):
+ name = max(values, key=lambda k: budget.size(values[k]))
+ del values[name]
+ rest = self._get_call(target, name, depth)
+ more[f"{obj_id}.{name}"] = (
+ f"left out to fit the response budget; {rest}"
+ )
+ if values:
+ entry["values"] = values
+ else:
+ entry.pop("values", None)
+ return reply
+
+ def _fit_result(self, value):
+ """A plain value (a method's result) cut to fit the budget."""
+ room = self._budget()
+ if budget.size(value) <= room:
+ return value
+ wrapped, cuts = budget.shrink({"result": value}, room - 120)
+ note = cuts.get("result", "shortened")
+ return {
+ "result": wrapped["result"],
+ "more": f"{note} to fit the response budget",
+ }
+
+ # -------------------------------------------------------------------------
+ # object_list and object_types
+ # -------------------------------------------------------------------------
+
+ def _catalog(self, graph):
+ """``{type name: TypeInfo}``: the types of the objects, those their
+ properties may hold (with visible subclasses), and the visible bases
+ they extend."""
+ pending = [
+ type(obj) for obj, _ in graph.objects.values() if obj is not self.state
+ ]
+ known, expanded = set(), set()
+ while pending:
+ cls = pending.pop()
+ if cls in known or not is_visible(cls):
+ continue
+ known.add(cls)
+ for prop in type_info(cls).properties.values():
+ if prop.reference:
+ for held in object_classes(prop.type_def):
+ if held not in expanded:
+ expanded.add(held)
+ pending.extend(subclasses(held))
+ for cls in list(known):
+ base = self._base(cls)
+ while base is not None and base not in known:
+ known.add(base)
+ base = self._base(base)
+ catalog = {type_name(cls): type_info(cls) for cls in known}
+ if self.state:
+ catalog[STATE_TYPE] = self.state.info
+ return dict(sorted(catalog.items()))
+
+ @staticmethod
+ def _base(klass):
+ """The nearest visible base of ``klass``, which it can extend."""
+ for base in klass.__mro__[1:]:
+ if is_visible(base):
+ return base
+ return None
+
+ def _render(self, info) -> dict:
+ """A type in full: what agents may use of it now."""
+ permissions = self._mcp.permissions
+ entry = {}
+ if info.description:
+ entry["description"] = info.description
+ properties = {}
+ for prop in self._readable(info).values():
+ item = prop.described()
+ writable = prop.writable and permissions.allows(prop.set_requires)
+ if not writable:
+ item["read_only"] = True
+ requires = prop.requires + (prop.set_requires if writable else ())
+ if requires:
+ item["requires"] = list(dict.fromkeys(requires))
+ properties[prop.name] = item
+ methods = {}
+ for method in info.methods.values():
+ if not permissions.allows(method.requires):
+ continue
+ fn = getattr(info.cls, method.attr)
+ item = {"parameters": function_input_schema(fn, ref=reference_schema)}
+ if method.description:
+ item = {"description": method.description, **item}
+ returns = type_to_schema(return_hint(fn), reference_schema)
+ if returns and returns != {"type": "null"}:
+ item["returns"] = returns
+ if method.read_only:
+ item["read_only"] = True
+ if method.annotations:
+ item["annotations"] = dict(method.annotations)
+ if method.requires:
+ item["requires"] = list(method.requires)
+ methods[method.name] = item
+ entry["properties"] = properties
+ entry["methods"] = methods
+ constructor = info.constructor
+ if constructor is not None and permissions.allows(constructor.requires):
+ item = {"parameters": self._constructor_schema(info)}
+ if constructor.description:
+ item["description"] = constructor.description
+ if constructor.requires:
+ item["requires"] = list(constructor.requires)
+ entry["constructor"] = item
+ if info.constructor_warning and info.cls not in self._warned:
+ self._warned.add(info.cls)
+ logger.warning(
+ "%s has no constructor for agents: %s",
+ info.cls.__name__,
+ info.constructor_warning,
+ )
+ return entry
+
+ def _rendered(self, catalog, include_inherited):
+ """``{name: entry}``: each type in full, or as what it adds to the
+ type it extends."""
+ full = {name: self._render(info) for name, info in catalog.items()}
+ result = {}
+ for name, info in catalog.items():
+ entry = full[name]
+ base = (
+ None if include_inherited or info.cls is None else self._base(info.cls)
+ )
+ if base is not None:
+ base_name = type_name(base)
+ if base_name not in full:
+ full[base_name] = self._render(type_info(base))
+ entry = _extending(entry, base_name, full[base_name])
+ result[name] = entry
+ return result
+
+ def _named(self, graph, short=False):
+ """``{name: {"type", "read_only"?, "description"?}}`` for the names agents
+ start from, in the order they were given. ``type`` is None while a name
+ holds nothing, and with ``short`` the description is only its first
+ sentence."""
+ named = {}
+ for name, (value, read_only) in graph.entries.items():
+ item = {"type": None if value is None else self._type(value)}
+ if read_only:
+ item["read_only"] = True
+ about = self._entries[name].description
+ if about and short:
+ about = _first_sentence(about)
+ if about:
+ item["description"] = about
+ named[name] = item
+ if self.state:
+ named[STATE_NAME] = {"type": STATE_TYPE}
+ return named
+
+ def list_objects(self, offset: Offset = 0):
+ items = list(self._named(self._graph()).items())
+ start = offset
+ # As many as fit, one at least, with room for the note
+ room = self._budget() - 200
+ used, end = budget.size({"objects": {}}), start
+ while end < len(items):
+ name, item = items[end]
+ used += budget.size({name: item})
+ if used > room and end > start:
+ break
+ end += 1
+ result = {"objects": dict(items[start:end])}
+ if end < len(items):
+ result["more"] = {
+ "objects": (
+ f"{start + 1}-{end} of {len(items)} listed to fit the response "
+ f"budget; object_list(offset={end}) lists the next ones"
+ )
+ }
+ return result
+
+ def types(self, type_names: TypeNames = None, include_inherited: bool = False):
+ graph = self._graph()
+ catalog = self._catalog(graph)
+ if type_names is None:
+ rendered = self._rendered(catalog, include_inherited)
+ index = {name: _index_entry(e) for name, e in rendered.items()}
+ return self._fit_index({"types": index})
+
+ known = {**typeinfo.type_names()[1], **dict.fromkeys(catalog)}
+ wanted, members, unknown = [], [], []
+ for raw in dict.fromkeys(type_names):
+ if raw in known:
+ wanted.append(raw)
+ else:
+ owner, _, member = raw.rpartition(".")
+ if owner in known and member:
+ members.append((owner, member))
+ else:
+ unknown.append(raw)
+
+ def info_of(name):
+ return catalog.get(name) or type_info(typeinfo.type_names()[1][name])
+
+ found, missing = [], []
+ for owner, member in members:
+ entry = self._render(info_of(owner))
+ section = next(
+ (k for k in ("properties", "methods") if member in entry[k]), None
+ )
+ if section is not None:
+ found.append((owner, section, member, entry[section][member]))
+ elif member == "constructor" and "constructor" in entry:
+ found.append((owner, None, member, entry["constructor"]))
+ else:
+ missing.append(f"{owner}.{member}")
+ # Every name that is wrong, in one reply
+ problems = []
+ if unknown:
+ problems.append(
+ f"Unknown types or members: {', '.join(unknown)}. Types: "
+ f"{', '.join(catalog)}; object_types() lists them."
+ )
+ if missing:
+ problems.append(
+ f"No member {', '.join(missing)}; object_types([type]) lists a "
+ f"type's properties and methods."
+ )
+ if problems:
+ raise NotFoundError(" ".join(problems))
+
+ selected = {name: info_of(name) for name in dict.fromkeys(wanted)}
+ rendered = self._rendered(selected, include_inherited) if selected else {}
+ for owner, section, member, value in found:
+ if section is None:
+ rendered.setdefault(owner, {})[member] = value
+ else:
+ rendered.setdefault(owner, {}).setdefault(section, {})[member] = value
+ result = {"types": rendered}
+ if budget.size(result) > self._budget():
+ types, cuts = budget.shrink(rendered, self._budget() - 200)
+ result = {"types": types}
+ if cuts:
+ result["more"] = dict.fromkeys(
+ cuts,
+ "shortened to fit the response budget; describe fewer types per call",
+ )
+ return result
+
+ def _fit_index(self, result):
+ room = self._budget()
+ if budget.size(result) <= room:
+ return result
+ for entry in result["types"].values():
+ entry.pop("properties", None)
+ entry.pop("methods", None)
+ note = (
+ 'member names left out to fit the response budget; object_types(["Type"]) '
+ "for a type's members"
+ )
+ if budget.size(result) > room:
+ types = list(result["types"].items())
+ keep = len(types)
+ while keep > 1 and budget.size(dict(types[:keep])) > room - 200:
+ keep //= 2
+ result["types"] = dict(types[:keep])
+ note = (
+ f"{keep} of {len(types)} types shown, member names left out, to fit "
+ f'the response budget; object_types(["Type"]) for one type'
+ )
+ result["more"] = {"types": note}
+ return result
+
+ def describe_class(self, cls):
+ """What agents see of ``cls`` now (``server.mcp.describe(cls)``)."""
+ if cls is None or cls == STATE_TYPE:
+ return self._render(self.state.info)
+ info = type_info(cls)
+ if not info.visible:
+ return None
+ return self._render(info)
+
+ # -------------------------------------------------------------------------
+ # object_get
+ # -------------------------------------------------------------------------
+
+ def get(
+ self, target: Target, properties: list[str] | None = None, depth: Depth = 1
+ ):
+ graph = self._graph()
+ value, writable = self._object(target, graph)
+ if properties is not None:
+ visible = list(self._readable(self._info(value)))
+ unknown = [p for p in properties if p not in visible]
+ if unknown:
+ msg = (
+ f"{self._label(value)} has no properties {unknown}; its properties: "
+ f"{', '.join(visible)}"
+ )
+ raise NotFoundError(msg)
+ return self._reply(
+ value,
+ graph,
+ depth,
+ target=target,
+ writable=writable,
+ properties=properties,
+ )
+
+ # -------------------------------------------------------------------------
+ # object_update
+ # -------------------------------------------------------------------------
+
+ async def update(self, target: Target, values: dict):
+ obj, writable = self._object(target, self._graph())
+ return await self._apply_update(obj, writable, values)
+
+ async def _apply_update(self, obj, writable, values, scope=None):
+ label = self._label(obj)
+ if not writable:
+ msg = f"Nothing was applied: {label} is exposed read-only."
+ raise PermissionError(msg)
+
+ info, permissions = self._info(obj), self._mcp.permissions
+ props = self._readable(info)
+ rejected, read_only = [], False
+ for name in values:
+ prop = props.get(name)
+ if prop is None:
+ rejected.append(f"{name} (unknown)")
+ elif not prop.writable:
+ rejected.append(f"{name} (read-only)")
+ read_only = True
+ elif not permissions.allows(prop.set_requires):
+ off = [n for n in prop.set_requires if not permissions.allows((n,))]
+ rejected.append(
+ f"{name} (read-only: permission {', '.join(off)} is off)"
+ )
+ read_only = True
+ if rejected:
+ writable_names = [
+ n
+ for n, p in props.items()
+ if p.writable and permissions.allows(p.set_requires)
+ ]
+ msg = (
+ f"Nothing was applied. Rejected on {label}: {', '.join(rejected)}. "
+ f"Writable: {', '.join(writable_names) or 'none'}"
+ )
+ # Methods may change what can't be written: point at them
+ methods = [
+ m.name for m in info.methods.values() if permissions.allows(m.requires)
+ ]
+ if read_only and methods:
+ msg += (
+ f". Methods: {', '.join(methods)}; "
+ f"object_types([{json.dumps(self._type(obj))}]) says what "
+ f"they do."
+ )
+ raise ValidationError(msg)
+
+ converted, errors = {}, []
+ resolve = self._resolver(scope, read_only=False)
+ for name, value in values.items():
+ prop = props[name]
+ try:
+ converted[name] = from_json(
+ validate(value, prop.schema, name),
+ prop.type_def,
+ resolve if prop.reference else None,
+ name,
+ )
+ except (ValidationError, PermissionError) as e:
+ errors.append(str(e))
+ if errors:
+ msg = f"Nothing was applied: {'; '.join(errors)}"
+ raise ValidationError(msg)
+
+ state = self._mcp.server.state
+ applied = []
+ with state:
+ # Fields and state keys first, all at once: they cannot fail
+ for name, value in converted.items():
+ if props[name].origin == "state":
+ state[name] = value
+ applied.append(name)
+ elif props[name].origin == "field":
+ setattr(obj, name, value)
+ applied.append(name)
+ # Then setters, in order: one that raises stops the update
+ for name, value in converted.items():
+ if props[name].origin != "property":
+ continue
+ try:
+ setattr(obj, name, value)
+ except Exception as e:
+ done = f"; applied: {', '.join(applied)}" if applied else ""
+ msg = f"Setting {label}.{name} failed: {error_text(e)}{done}"
+ raise ToolError(msg) from e
+ applied.append(name)
+ await _settle(obj)
+ return {"id": obj._id, "updated": list(converted)}
+
+ # -------------------------------------------------------------------------
+ # object_call
+ # -------------------------------------------------------------------------
+
+ def _method(self, obj, writable, method, target):
+ info = self._info(obj)
+ permissions = self._mcp.permissions
+ found = info.methods.get(method)
+ if found is None:
+ type_name = self._type(obj)
+ msg = (
+ f"{target} (type {type_name}) has no method {json.dumps(method)}; "
+ f'object_types(["{type_name}"]) lists its methods.'
+ )
+ raise NotFoundError(msg)
+ if not writable and not found.read_only:
+ allowed = [n for n, m in info.methods.items() if m.read_only]
+ msg = (
+ f"{self._label(obj)} is exposed read-only; only read-only methods can "
+ f"be called: {', '.join(allowed) or 'none'}"
+ )
+ raise PermissionError(msg)
+ permissions.require(*found.requires, what=f"{self._type(obj)}.{found.name}")
+ return found
+
+ async def call(self, target: Target, method: str, args: dict | None = None):
+ # object_call skips the protocol's lock: the method's own concurrent
+ # option decides, so it is looked up first, then again under the
+ # lock, where the objects are as earlier calls left them.
+ obj, writable = self._object(target, self._graph())
+ found = self._method(obj, writable, method, target)
+ async with self._mcp.protocol.locked(found.concurrent):
+ obj, writable = self._object(target, self._graph())
+ found = self._method(obj, writable, method, target)
+ _, encoded = await self._invoke(obj, found, args, "args")
+ return encoded
+
+ async def _invoke(self, obj, method, args, label, scope=None):
+ """Call an exposed method: bind, resolve object ids, run, settle, and
+ encode what it returns."""
+ fn = getattr(obj, method.attr)
+ schema = function_input_schema(fn, ref=reference_schema)
+ try:
+ args = bind_arguments(fn, args, schema, label=label)
+ except ValidationError as e:
+ msg = f"Invalid arguments for {self._type(obj)}.{method.name}: {e}"
+ raise ValidationError(msg) from None
+ args = self.resolve_arguments(
+ fn, args, read_only=method.read_only, scope=scope, label=label
+ )
+ result = fn(**progress.inject(fn, args))
+ if inspect.isawaitable(result):
+ result = await result
+ await _settle(obj)
+ return result, self._encode_result(result, self._graph(scope))
+
+ # -------------------------------------------------------------------------
+ # object_batch
+ # -------------------------------------------------------------------------
+
+ def _constructor_schema(self, info):
+ constructor = info.constructor
+ if constructor.attr is not None:
+ fn = getattr(info.cls, constructor.attr)
+ return function_input_schema(
+ fn, skip=(constructor.server,), ref=reference_schema
+ )
+ properties = {
+ prop.name: prop.described()
+ for prop in self._readable(info).values()
+ if prop.origin == "field" and prop.writable
+ }
+ return {
+ "type": "object",
+ "properties": properties,
+ "additionalProperties": False,
+ }
+
+ def _constructible(self, graph):
+ """Types with a constructor, by name."""
+ return {
+ name: info
+ for name, info in self._catalog(graph).items()
+ if info.constructor is not None
+ }
+
+ @staticmethod
+ def _references(value):
+ """Every "@..." reference string inside a step value."""
+ if isinstance(value, str):
+ if value.startswith("@") and not value.startswith("@@"):
+ yield value
+ elif isinstance(value, list):
+ for item in value:
+ yield from ObjectLayer._references(item)
+ elif isinstance(value, dict):
+ for item in value.values():
+ yield from ObjectLayer._references(item)
+
+ def _check_steps(self, steps):
+ """Validate every step before any runs, and return the types that can
+ be built."""
+
+ def fail(message):
+ msg = f"Nothing was applied: {message}"
+ raise ValidationError(msg)
+
+ graph = self._graph()
+ constructible = None
+ defined = set()
+ built = {} # "as" name of a new step -> its TypeInfo
+ for index, step in enumerate(steps):
+ path = f"steps[{index}]"
+ step_types = [step_type for step_type in _STEP_KEYS if step_type in step]
+ if len(step_types) != 1:
+ fail(f"{path}: a step has exactly one of 'new', 'call' or 'update'")
+ step_type = step_types[0]
+ unexpected = sorted(set(step) - set(_STEP_KEYS[step_type]))
+ if unexpected:
+ fail(
+ f"{path}: unexpected {unexpected}; {step_type} steps take "
+ f"{list(_STEP_KEYS[step_type])}"
+ )
+ if not isinstance(step[step_type], str) or not step[step_type]:
+ fail(f"{path}.{step_type}: expected a non-empty string")
+ if step_type == "call" and (
+ not isinstance(step.get("method"), str) or not step["method"]
+ ):
+ fail(f"{path}: a call step needs 'method'")
+ if step_type == "update" and not isinstance(step.get("values"), dict):
+ fail(
+ f"{path}: an update step needs 'values', an object of property values"
+ )
+ if step.get("args") is not None and not isinstance(step["args"], dict):
+ fail(f"{path}.args: expected an object")
+ if step_type == "new":
+ if constructible is None:
+ constructible = self._constructible(graph)
+ name = step["new"]
+ if name not in constructible:
+ fail(
+ f"{path}: no type {json.dumps(name)} can be built; types with a "
+ f"constructor: {', '.join(constructible) or 'none'}"
+ )
+ info = constructible[name]
+ self._check_permissions(
+ info.constructor.requires, f"{path} (new {name})"
+ )
+ if "as" in step:
+ built[step["as"]] = info
+ checked = [step.get("args")]
+ else:
+ checked = [step[step_type], step.get("args"), step.get("values")]
+ info = self._info_before_run(step[step_type], built, graph)
+ if info is not None and step_type == "call":
+ method = info.methods.get(step["method"])
+ if method is not None:
+ what = f"{path} (call {step['method']} on {step[step_type]})"
+ self._check_permissions(method.requires, what)
+ if info is not None and step_type == "update":
+ for prop_name in step["values"]:
+ prop = info.properties.get(prop_name)
+ if prop is not None:
+ what = f"{path} (update {prop_name} on {step[step_type]})"
+ self._check_permissions(
+ prop.requires + prop.set_requires, what
+ )
+ for reference in self._references(checked):
+ if reference[1:].split(".")[0] not in defined:
+ fail(
+ f'{path}: {reference!r} names no earlier step (give that step "as")'
+ )
+ if "as" in step:
+ name = step["as"]
+ if not isinstance(name, str) or not _STEP_NAME.match(name):
+ fail(
+ f"{path}.as: expected a name of letters, digits and underscores"
+ )
+ if name in defined:
+ fail(f"{path}.as: {name!r} already names an earlier step")
+ defined.add(name)
+ return constructible or {}
+
+ def _check_permissions(self, requires, what):
+ try:
+ self._mcp.permissions.require(*requires, what=what)
+ except PermissionDeniedError as e:
+ msg = f"Nothing was applied: {e}"
+ raise PermissionDeniedError(msg) from None
+
+ def _info_before_run(self, target, built, graph):
+ """The type of a step's target when it is known before the batch
+ runs: an object reachable now, or "@name" of a new step."""
+ if target.startswith("@") and not target.startswith("@@"):
+ return built.get(target[1:])
+ try:
+ obj, _ = self._object(target.removeprefix("@"), graph)
+ except LookupError:
+ return None
+ return self._info(obj)
+
+ def _follow(self, reference, scope, path):
+ """The value an "@name.seg..." reference stands for."""
+ name, *segments = reference[1:].split(".")
+ value = scope.names[name]
+ walked = f"@{name}"
+ for segment in segments:
+ if is_object(value) or value is self.state:
+ prop = self._readable(self._info(value)).get(segment)
+ if prop is None:
+ msg = (
+ f"{path}: {walked} (type {self._type(value)}) has no "
+ f"property {segment!r}"
+ )
+ raise NotFoundError(msg)
+ value = self._read(value, prop)
+ if prop.reference: # as object_get shows it: objects only
+ if isinstance(value, (list, tuple)):
+ value = [
+ v for v in value if not is_object(v) or self._is_object(v)
+ ]
+ elif is_object(value) and not self._is_object(value):
+ value = None
+ elif isinstance(value, dict):
+ if segment not in value:
+ msg = f"{path}: {walked} has no key {segment!r}"
+ raise NotFoundError(msg)
+ value = value[segment]
+ elif isinstance(value, (list, tuple)):
+ try:
+ value = value[int(segment)]
+ except (ValueError, IndexError):
+ msg = (
+ f"{path}: {walked} has {len(value)} items, no index {segment!r}"
+ )
+ raise NotFoundError(msg) from None
+ else:
+ type_name = "null" if value is None else type(value).__name__
+ msg = f"{path}: {walked} is {type_name}, which has no {segment!r}"
+ raise NotFoundError(msg)
+ walked = f"{walked}.{segment}"
+ return value
+
+ def _substitute(self, value, scope, path, ids=True):
+ """``value`` with its references resolved. With ``ids``, objects become their
+ ids, since arguments travel as JSON."""
+ if isinstance(value, str):
+ if value.startswith("@@"):
+ return value[1:]
+ if value.startswith("@"):
+ value = self._follow(value, scope, path)
+ return self._as_ids(value) if ids else value
+ return value
+ if isinstance(value, list):
+ return [
+ self._substitute(v, scope, f"{path}[{i}]", ids)
+ for i, v in enumerate(value)
+ ]
+ if isinstance(value, dict):
+ return {
+ k: self._substitute(v, scope, f"{path}.{k}", ids)
+ for k, v in value.items()
+ }
+ return value
+
+ def _as_ids(self, value):
+ if is_object(value) or value is self.state:
+ return value._id
+ if isinstance(value, (list, tuple)):
+ return [self._as_ids(v) for v in value]
+ if isinstance(value, dict):
+ return {k: self._as_ids(v) for k, v in value.items()}
+ return value
+
+ def _target(self, target, scope, path):
+ """``(object, writable)`` for a step's target: a name, an id, or a
+ reference to an object."""
+ target = self._substitute(target, scope, path, ids=False)
+ graph = self._graph(scope)
+ if is_object(target) or target is self.state:
+ found = graph.objects.get(target._id)
+ if found is None or found[0] is not target:
+ msg = f"{path}: {self._label(target)} is not reachable"
+ raise NotFoundError(msg)
+ return found
+ if not isinstance(target, str):
+ msg = f"{path}: the target is {type(target).__name__}, not an object"
+ raise NotFoundError(msg)
+ return self._object(target, graph)
+
+ async def _build(self, info, args, scope, label):
+ cls, constructor = info.cls, info.constructor
+ self._mcp.permissions.require(
+ *constructor.requires, what=f"{type_name(cls)} constructor"
+ )
+ schema = self._constructor_schema(info)
+ if constructor.attr is None:
+ values = validate(args or {}, schema, label)
+ resolve = self._resolver(scope, read_only=False)
+ for name, given in values.items():
+ prop = info.properties[name]
+ values[name] = from_json(
+ given,
+ prop.type_def,
+ resolve if prop.reference else None,
+ f"{label}.{name}",
+ )
+ instance = cls(self._mcp.server, **values)
+ else:
+ fn = getattr(cls, constructor.attr)
+ args = bind_arguments(fn, args, schema, label=label, positional=(None,))
+ args = self.resolve_arguments(fn, args, scope=scope, label=label)
+ instance = fn(self._mcp.server, **args)
+ if inspect.isawaitable(instance):
+ instance = await instance
+ if not isinstance(instance, cls):
+ msg = (
+ f"{cls.__name__}.{constructor.attr} returned an object of type "
+ f"{type(instance).__name__}, not {cls.__name__}"
+ )
+ raise TypeError(msg)
+ scope.built[instance._id] = instance
+ await _settle(instance)
+ return instance
+
+ async def _run_step(self, step_type, step, scope, path, constructible):
+ """Run one step and return its result, which the step's ``as`` can name."""
+ if step_type == "new":
+ info = constructible[step["new"]]
+ label = f"{path}.args"
+ args = self._substitute(step.get("args"), scope, label)
+ return await self._build(info, args, scope, label)
+
+ obj, writable = self._target(step[step_type], scope, f"{path}.{step_type}")
+ if step_type == "update":
+ values = self._substitute(step["values"], scope, f"{path}.values")
+ return await self._apply_update(obj, writable, values, scope)
+ method = self._method(obj, writable, step["method"], step[step_type])
+ args = self._substitute(step.get("args"), scope, f"{path}.args")
+ raw, _ = await self._invoke(obj, method, args, f"{path}.args", scope)
+ return raw
+
+ async def batch(
+ self, steps: list[dict], results: Literal["links", "full"] = "links"
+ ):
+ links = results == "links"
+ constructible = self._check_steps(steps)
+ scope = _Scope()
+ step_results = []
+ # Progress counts steps, and a method's own reports count within its step
+ reporter = progress.current()
+ for index, step in enumerate(steps):
+ if index:
+ await asyncio.sleep(0) # a cancel lands between steps
+ step_type = next(k for k in _STEP_KEYS if k in step)
+ path = f"steps[{index}]"
+ try:
+ with progress.reporting(progress.batch_step(index, len(steps))):
+ raw = await self._run_step(
+ step_type, step, scope, path, constructible
+ )
+ except Exception as e:
+ applied = None
+ if step_results:
+ applied = self._reply(
+ {"results": step_results},
+ self._graph(scope),
+ links=links,
+ spread=True,
+ )
+ failure = _batch_failure(index, step_type, step, e, applied)
+ raise BatchError(failure) from e
+ step_results.append(raw)
+ if "as" in step:
+ scope.names[step["as"]] = raw
+ if reporter is not None:
+ await reporter(index + 1, total=len(steps))
+ graph = self._graph()
+ unattached = [
+ instance
+ for instance in scope.built.values()
+ if instance._id not in graph.objects
+ ]
+ result = {"results": step_results}
+ if unattached:
+ result["unattached"] = unattached
+ # Objects as they are once every step ran, each read once
+ reply = self._reply(result, self._graph(scope), links=links, spread=True)
+ for key in ("results", "unattached"):
+ if key in reply.get("more", {}):
+ reply["more"][key] += "; run fewer steps per batch"
+ return reply
+
+ # -------------------------------------------------------------------------
+ # Registration, instructions, audit
+ # -------------------------------------------------------------------------
+
+ def _ensure_tools(self):
+ if self._registered:
+ return
+ self._registered = True
+
+ add = self._mcp._add_builtin_tool
+ read = {"readOnlyHint": True}
+ add(self.list_objects, "object_list", LIST_DESCRIPTION, read)
+ add(self.types, "object_types", TYPES_DESCRIPTION, read)
+ add(self.get, "object_get", GET_DESCRIPTION, read)
+ add(self.update, "object_update", UPDATE_DESCRIPTION, {"idempotentHint": True})
+ # call() takes the lock itself, so that each method's option decides
+ add(self.call, "object_call", CALL_DESCRIPTION, concurrent=True)
+ # The whole batch holds the call lock, once
+ add(self.batch, "object_batch", BATCH_DESCRIPTION)
+
+ def instructions(self):
+ """The lines the connection instructions give about the objects."""
+ try:
+ named = self._named(self._graph(), short=True)
+ except Exception:
+ logger.exception("Listing the objects for the instructions failed")
+ return []
+ if not named:
+ return []
+
+ def label(item):
+ text = item["type"] or "empty"
+ if item.get("read_only"):
+ text += ", read-only"
+ if item.get("description"):
+ text += f": {item['description']}"
+ return text
+
+ items = list(named.items())
+ shown = ", ".join(
+ f"{name} ({label(item)})" for name, item in items[:MAX_LISTED]
+ )
+ if len(items) > MAX_LISTED:
+ shown += f", and {len(items) - MAX_LISTED} more"
+ return [
+ f"Objects: {shown}; object_list() lists them, object_types() describes "
+ f"their types."
+ ]
+
+ def start(self):
+ """Called when the server starts: settle the type names, warning about
+ collisions. A class defined later is warned about once agents look at types."""
+ typeinfo.type_names()
+
+ def audit(self):
+ """Log likely exposure mistakes once the app is set up."""
+ if not self.exposes_anything():
+ return
+ try:
+ catalog = self._catalog(self._graph())
+ except Exception:
+ logger.exception("Invalid object exposure")
+ return
+
+ permissions = self._mcp.permissions
+ for name, info in catalog.items():
+ needs = {f"{name}.{m.attr}": m.requires for m in info.methods.values()}
+ for prop in info.properties.values():
+ needs[f"{name}.{prop.name}"] = prop.requires + prop.set_requires
+ if info.constructor is not None:
+ needs[f"{name} constructor"] = info.constructor.requires
+ for what, requires in needs.items():
+ unknown = [n for n in requires if n not in permissions]
+ if unknown:
+ logger.warning(
+ "%s requires undeclared permissions %s; it is never offered",
+ what,
+ unknown,
+ )
+ for field_name, held in info.hidden_references.items():
+ visible = sorted(
+ type_name(k) for t in held for k in subclasses(t) if is_visible(k)
+ )
+ if visible:
+ logger.warning(
+ "%s.%s holds objects agents see (%s) but is not exposed, so "
+ "they are unreachable through it; expose it, or hide it "
+ "explicitly with mcp=False",
+ name,
+ field_name,
+ ", ".join(visible),
+ )
+
+
+def _objects_within(value, is_obj, limit=None):
+ """The objects in ``value``, at any depth of lists, tuples, sets and dict
+ values. ``limit`` keeps the first items of each list or tuple, as a
+ capped value shows them."""
+ if is_obj(value):
+ yield value
+ elif isinstance(value, (list, tuple)):
+ for item in value[:limit]:
+ yield from _objects_within(item, is_obj, limit)
+ elif isinstance(value, (set, frozenset)):
+ for item in value:
+ yield from _objects_within(item, is_obj, limit)
+ elif isinstance(value, dict):
+ for item in value.values():
+ yield from _objects_within(item, is_obj, limit)
+
+
+def _holds_objects(value):
+ return next(_objects_within(value, is_object), None) is not None
+
+
+# -----------------------------------------------------------------------------
+# object_types' index
+# -----------------------------------------------------------------------------
+
+# The end of a sentence: a period followed by a capital or the end (so not
+# "e.g. a"), or by the paragraph's end
+_SENTENCE_END = re.compile(r"[.!?](?=\s+[A-Z`(\"']|\s*$)")
+MAX_ABOUT = 200
+
+
+def _first_sentence(text):
+ text = " ".join((text or "").split())
+ match = _SENTENCE_END.search(text)
+ sentence = text[: match.end()] if match else text
+ if len(sentence) > MAX_ABOUT:
+ sentence = sentence[: MAX_ABOUT - 1] + "…"
+ return sentence
+
+
+def _extending(entry, base_name, base):
+ """``entry`` as what it adds to, changes in or drops from ``base``. What it
+ lacks is False, including the constructor when it lost the base's."""
+ delta = {"extends": base_name}
+ if "description" in entry:
+ delta["description"] = entry["description"]
+ for key in ("properties", "methods"):
+ delta[key] = {k: v for k, v in entry[key].items() if base[key].get(k) != v}
+ delta[key].update((k, False) for k in base[key] if k not in entry[key])
+ if entry.get("constructor") != base.get("constructor"):
+ delta["constructor"] = entry.get("constructor", False)
+ return delta
+
+
+def _index_entry(entry):
+ """A type as the index lists it: what it extends, the first sentence of its
+ description, its own property and method names, those of its base that it
+ lacks, and its constructor (False when it lost the base's)."""
+ index, lacks = {}, []
+ about = _first_sentence(entry.get("description"))
+ if about:
+ index["about"] = about
+ for key in ("properties", "methods"):
+ names = [k for k, v in entry.get(key, {}).items() if v is not False]
+ lacks.extend(k for k, v in entry.get(key, {}).items() if v is False)
+ if names:
+ index[key] = names
+ if lacks:
+ index["lacks"] = lacks
+ if "constructor" in entry:
+ index["constructor"] = entry["constructor"] is not False
+ if "extends" in entry:
+ index["extends"] = entry["extends"]
+ return index
+
+
+# -----------------------------------------------------------------------------
+# object_batch's results
+# -----------------------------------------------------------------------------
+
+
+def _batch_failure(index, step_type, step, error, results):
+ if not isinstance(error, (ValueError, LookupError, PermissionError)):
+ logger.error("object_batch step %d raised", index, exc_info=error)
+ reason = error_text(error)
+ if step_type == "new":
+ what = f"new {step['new']}"
+ elif step_type == "call":
+ what = f"call {step['method']} on {step['call']}"
+ else:
+ what = f"update {step['update']}"
+ message = f"steps[{index}] ({what}) failed: {reason}"
+ if not results: # the first step: its own error says what it did
+ return message
+ if not message.endswith("."):
+ message += "."
+ applied = json.dumps(results, default=repr)
+ if index == 1:
+ return f"{message} Step 0 stays applied (no rollback); its result: {applied}"
+ return (
+ f"{message} Steps 0-{index - 1} stay applied (no rollback); "
+ f"their results: {applied}"
+ )
+
+
+def _is_reference(value) -> bool:
+ return isinstance(value, dict) and "id" in value and value.keys() <= {"id", "type"}
+
+
+def _holds_references(value) -> bool:
+ """Whether a rendered value is a reference or a list of them. Those are the
+ values an object keeps with ``results: "links"``."""
+ if _is_reference(value):
+ return True
+ return isinstance(value, list) and bool(value) and all(map(_is_reference, value))
diff --git a/src/trame_server/mcp/permissions.py b/src/trame_server/mcp/permissions.py
new file mode 100644
index 0000000..2e8e4fd
--- /dev/null
+++ b/src/trame_server/mcp/permissions.py
@@ -0,0 +1,275 @@
+"""Permissions: capabilities that the people running an application can
+withhold from agents (``mcp.permissions``, ``--mcp-deny``).
+
+The application declares each capability it controls, and names the
+permissions that a tool, a method, a property or a constructor needs with
+``requires=``:
+
+.. code-block:: python
+
+ server.mcp.permissions.declare("files", "Read files and folders on this computer")
+ server.mcp.permissions.declare(
+ "scripts", "Run Python code the agent writes", requires="files"
+ )
+
+
+ @mcp.method(requires="files")
+ def list_files(self, path: str) -> dict: ...
+
+While a permission is denied, what needs it is left out of what agents are
+offered (``tools/list``, ``object_types``), and calls to it are refused
+with :class:`PermissionDeniedError`. A client that listed the tools
+earlier still has them, and nothing tells it the list changed.
+``require()`` checks inside a call, for a need that depends on the
+arguments.
+
+``requires`` on a permission means what it means on a tool: the
+permission is allowed only while the ones it requires are, typically
+because it grants them anyway (a script can read files). Allowing it while
+one of them stays denied raises, and denying one denies the ones requiring
+it, so no setting holds one without the other.
+
+``--mcp-deny NAME[,NAME]`` (repeatable) and ``TRAME_MCP_DENY`` deny
+permissions for the whole run. Whoever launched the application decided,
+and neither its code nor its UI can allow them again (``locked`` tells a
+UI which switches to disable), unless they also gave ``--mcp-mutable
+deny``: the permissions then start denied, and the application may allow
+them once the server runs. A name the application does not declare
+refuses every agent call once the server runs: the user meant to withhold
+something, and a typo must not leave it allowed.
+"""
+
+from __future__ import annotations
+
+import logging
+from collections.abc import Mapping
+from dataclasses import dataclass
+
+from trame_common.obj.mcp import permission_names
+
+logger = logging.getLogger("trame_server.mcp")
+
+__all__ = ["PermissionDeniedError", "Permissions"]
+
+
+class PermissionDeniedError(PermissionError):
+ """A call needs a permission that is denied (``mcp.permissions``)."""
+
+
+@dataclass
+class _Permission:
+ description: str
+ requires: tuple[str, ...]
+ allowed: bool
+
+
+class Permissions(Mapping):
+ """The declared permissions (``mcp.permissions``), as a mapping from each
+ name to whether agents are allowed it. Assign ``permissions[name] =
+ bool``, or call :meth:`update` to set several at once, at any time."""
+
+ def __init__(self):
+ self._declared: dict[str, _Permission] = {}
+ self._launch_denied = frozenset()
+ self._launch_mutable = False # --mcp-mutable deny
+ self._started = False
+
+ def __getitem__(self, name) -> bool:
+ return self._get(name).allowed
+
+ def __iter__(self):
+ return iter(self._declared)
+
+ def __len__(self):
+ return len(self._declared)
+
+ def __setitem__(self, name, allowed):
+ self.update({name: allowed})
+
+ def __repr__(self):
+ return f"Permissions({dict(self)!r})"
+
+ def declare(self, name, description, *, requires=None, allowed=True):
+ """Declare a permission, allowed unless ``allowed=False``.
+
+ :param description: what it lets an agent do, in a few words. An agent
+ reads it when a call is refused.
+ :param requires: the permissions, declared earlier, that must be allowed
+ for this one to be, such as those it grants anyway. It starts denied
+ when one of them is denied.
+ """
+ if not isinstance(name, str) or not name:
+ msg = f"A permission name is a non-empty string, got {name!r}"
+ raise TypeError(msg)
+ if name in self._declared:
+ msg = f"The permission {name!r} is already declared"
+ raise ValueError(msg)
+ requires = permission_names(requires)
+ unknown = [n for n in requires if n not in self._declared]
+ if unknown:
+ msg = f"{name!r} requires {unknown}, which are not declared (declare them first)"
+ raise ValueError(msg)
+ allowed = (
+ bool(allowed)
+ and name not in self._launch_denied
+ and all(self._declared[n].allowed for n in requires)
+ )
+ self._declared[name] = _Permission(str(description), requires, allowed)
+
+ def update(self, values=(), /, **kwargs):
+ """Allow (True) or deny (False) several permissions at once, all or
+ none.
+
+ A permission is allowed only with those it requires: allowing one
+ while one of them stays denied raises ``ValueError``, so allow both
+ in the same call. Denying one also denies those requiring it. A
+ permission that is ``locked`` stays denied.
+ """
+ changes = {**dict(values), **kwargs}
+ for name in changes:
+ self._get(name)
+ deny = self._closure({n for n, v in changes.items() if not v}, self._requiring)
+ # Locked ones are left out (what requires a locked one is locked too)
+ allowing = {n for n, v in changes.items() if v}
+ held = allowing & set(self.locked)
+ allowed = allowing - held
+
+ def ends_allowed(name):
+ return name in allowed or (
+ self._declared[name].allowed and name not in deny
+ )
+
+ missing = {}
+ for name in self._ordered(allowed):
+ needed = self._closure(self._declared[name].requires, self._required)
+ needed = [r for r in self._ordered(needed) if not ends_allowed(r)]
+ if needed:
+ missing[name] = needed
+ if missing:
+ needs = "; ".join(
+ f"{name!r} requires {', '.join(map(repr, needed))}"
+ for name, needed in missing.items()
+ )
+ msg = (
+ f"Cannot allow what requires a denied permission ({needs}); allow "
+ f"them in the same update"
+ )
+ raise ValueError(msg)
+ if held:
+ logger.info(
+ "Not allowing %s: denied at launch (--mcp-deny)",
+ ", ".join(sorted(held)),
+ )
+ for name in allowed:
+ self._declared[name].allowed = True
+ for name in deny:
+ self._declared[name].allowed = False
+
+ @property
+ def locked(self) -> tuple[str, ...]:
+ """The permissions denied at launch, and those requiring them: denied
+ whatever is assigned. Empty once the server runs with ``--mcp-mutable
+ deny``."""
+ if self._started and self._launch_mutable:
+ return ()
+ held = self._closure(
+ self._launch_denied & self._declared.keys(), self._requiring
+ )
+ return self._ordered(held)
+
+ @property
+ def denied(self) -> tuple[str, ...]:
+ """The names of the denied permissions, in declaration order."""
+ return tuple(name for name, p in self._declared.items() if not p.allowed)
+
+ def description(self, name) -> str:
+ return self._get(name).description
+
+ def allows(self, names) -> bool:
+ """Whether every permission in ``names`` is declared and allowed."""
+ return all(
+ name in self._declared and self._declared[name].allowed for name in names
+ )
+
+ def require(self, *names, what="This call"):
+ """Raise :class:`PermissionDeniedError` unless every permission in ``names`` is
+ allowed. ``what`` names the refused action."""
+ for name in names:
+ permission = self._declared.get(name)
+ if permission is None:
+ msg = f'{what}: permission "{name}" was never declared by the app'
+
+ raise PermissionDeniedError(msg)
+ if not permission.allowed:
+ msg = (
+ f'{what}: permission "{name}" ({permission.description}) is off; '
+ f"only the people running the app can turn it on."
+ )
+ raise PermissionDeniedError(msg)
+
+ # -------------------------------------------------------------------------
+ # Launch options and lifecycle (driven by the MCP)
+ # -------------------------------------------------------------------------
+
+ def _deny_at_launch(self, names, mutable=False):
+ self._launch_denied = frozenset(names)
+ self._launch_mutable = mutable
+
+ def _start(self):
+ """Called when the server starts: report the launch names that match no
+ permission. From then on, they refuse every agent call."""
+ self._started = True
+ unknown = self._unknown_at_launch()
+ if unknown:
+ logger.error(
+ "--mcp-deny names %s, which this application does not declare "
+ "(it declares: %s); every agent call is refused",
+ ", ".join(unknown),
+ ", ".join(self._declared) or "none",
+ )
+
+ def _unknown_at_launch(self) -> list[str]:
+ return sorted(self._launch_denied - self._declared.keys())
+
+ def _check_launch(self):
+ """Refuse agent calls while a launch name matches no permission."""
+ unknown = self._started and self._unknown_at_launch()
+ if unknown:
+ msg = (
+ f"Agent access is refused: the application was launched denying "
+ f"{', '.join(unknown)}, which it does not declare"
+ )
+ raise PermissionDeniedError(msg)
+
+ # -------------------------------------------------------------------------
+ # Helpers
+ # -------------------------------------------------------------------------
+
+ def _get(self, name) -> _Permission:
+ try:
+ return self._declared[name]
+ except (KeyError, TypeError):
+ msg = (
+ f"No permission {name!r} is declared; declared: {list(self._declared)}"
+ )
+ raise KeyError(msg) from None
+
+ def _ordered(self, names) -> tuple[str, ...]:
+ """``names`` in declaration order."""
+ return tuple(name for name in self._declared if name in names)
+
+ def _required(self, name):
+ return self._declared[name].requires
+
+ def _requiring(self, name):
+ return [n for n, p in self._declared.items() if name in p.requires]
+
+ @staticmethod
+ def _closure(names, step) -> set[str]:
+ found, stack = set(), list(names)
+ while stack:
+ name = stack.pop()
+ if name not in found:
+ found.add(name)
+ stack.extend(step(name))
+ return found
diff --git a/src/trame_server/mcp/progress.py b/src/trame_server/mcp/progress.py
new file mode 100644
index 0000000..e9e7439
--- /dev/null
+++ b/src/trame_server/mcp/progress.py
@@ -0,0 +1,164 @@
+"""Progress notifications: what a tool or method reports through its
+``Progress`` parameter, sent to the agent that asked for it.
+
+A request carrying a ``progressToken`` in its ``_meta`` gets a
+:class:`Reporter` for its duration, when its transport can send
+notifications (``MCPProtocol.handle``'s ``notify``). The request's calls find
+it in a context variable, which follows them into the tasks they create.
+:func:`inject` passes it to a function that declares a ``Progress``
+parameter, or passes a reporter that does nothing when the agent asked for no
+progress.
+
+MCP requires the value sent to grow, and nothing to be sent after the result.
+So a report whose value doesn't grow is dropped, and its message goes with the
+next one. Reports are also combined into at most one notification per
+``MIN_INTERVAL``, the latest winning. The last one still waiting when the
+call returns goes out just before the result.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import contextlib
+import contextvars
+import logging
+
+from trame_common.obj.mcp import Progress
+
+from trame_server.mcp.schema import progress_parameter
+
+logger = logging.getLogger("trame_server.mcp")
+
+__all__ = ["Reporter", "inject", "reporting"]
+
+# Seconds between two notifications of one request, at least
+MIN_INTERVAL = 0.1
+
+# The decimal places by which a batch step's report without a total moves the
+# value: about half a float's precision, leaving the other half for the steps
+STEP_DIGITS = 8
+
+_NO_PROGRESS = Progress()
+_current = contextvars.ContextVar("trame_mcp_progress", default=None)
+
+
+class Reporter(Progress):
+ """Sends a request's progress with ``send(fields)``, an async callable
+ taking the notification's ``progress``, ``total`` and ``message``."""
+
+ def __init__(self, send, interval=MIN_INTERVAL):
+ self._send = send
+ self._interval = interval
+ self._sent = None # the last value sent
+ self._pending = None # (value, total) not sent yet
+ self._message = None # goes with the next notification
+ self._next = 0.0 # loop time from which the next one may go
+ self._flush = None # the task sending what is pending, when due
+ self._sending = asyncio.Lock()
+ self._closed = False
+
+ async def __call__(self, value, total=None, message=None):
+ if self._closed:
+ return
+ if message is not None:
+ self._message = message
+ latest = self._pending[0] if self._pending else self._sent
+ if latest is not None and not value > latest:
+ return
+ self._pending = (value, total)
+ if self._flush is not None:
+ return # going out when due, as the latest
+ delay = self._next - asyncio.get_running_loop().time()
+ if delay <= 0:
+ await self._send_pending()
+ else:
+ self._flush = asyncio.ensure_future(self._send_later(delay))
+
+ async def _send_later(self, delay):
+ await asyncio.sleep(delay)
+ self._flush = None
+ # Shielded: closing waits for a notification being written
+ await asyncio.shield(self._send_pending())
+
+ async def _send_pending(self):
+ async with self._sending:
+ if self._closed or self._pending is None:
+ return
+ value, total = self._pending
+ fields = {"progress": value}
+ if total is not None:
+ fields["total"] = total
+ if self._message is not None:
+ fields["message"] = self._message
+ self._pending, self._message, self._sent = None, None, value
+ self._next = asyncio.get_running_loop().time() + self._interval
+ try:
+ await self._send(fields)
+ except Exception: # the client went away: the call goes on
+ logger.debug("Sending progress failed", exc_info=True)
+ self._closed = True
+
+ async def close(self):
+ """Called when the result is ready: send what is pending now, before the
+ result, and nothing after it."""
+ if self._flush is not None:
+ self._flush.cancel()
+ self._flush = None
+ await self._send_pending()
+ async with self._sending:
+ self._closed = True
+
+
+class _BatchStep(Progress):
+ """The reporter a method gets during one step of an ``object_batch``. Its
+ reports become progress within that step of the batch (step k of n).
+ With a total, the value moves by the method's fraction of the step;
+ without one, each report moves it by ``10**-STEP_DIGITS``, so that it
+ still grows and goes out with its message."""
+
+ def __init__(self, batch, index, count):
+ self._batch = batch
+ self._index = index
+ self._count = count
+ self._done = index # the furthest within this step
+
+ async def __call__(self, value, total=None, message=None):
+ if total:
+ done = self._index + min(max(value / total, 0.0), 1.0)
+ else:
+ tick = 10**-STEP_DIGITS
+ done = min(round(self._done + tick, STEP_DIGITS), self._index + 1 - tick)
+ self._done = max(self._done, done)
+ await self._batch(done, total=self._count, message=message)
+
+
+@contextlib.contextmanager
+def reporting(reporter):
+ """Make ``reporter`` the reporter of the calls made in the block (None when
+ the agent asked for no progress)."""
+ token = _current.set(reporter)
+ try:
+ yield
+ finally:
+ _current.reset(token)
+
+
+def batch_step(index, count):
+ """The reporter that the method of step ``index`` of ``count`` gets in a batch,
+ or None when the agent asked for no progress."""
+ batch = _current.get()
+ return None if batch is None else _BatchStep(batch, index, count)
+
+
+def current():
+ """The reporter of the request being handled, or None."""
+ return _current.get()
+
+
+def inject(fn, arguments):
+ """``arguments``, with the reporter added when ``fn`` declares a
+ ``Progress`` parameter: the request's, or one that does nothing."""
+ name = progress_parameter(fn)
+ if name is None:
+ return arguments
+ return {**arguments, name: _current.get() or _NO_PROGRESS}
diff --git a/src/trame_server/mcp/protocol.py b/src/trame_server/mcp/protocol.py
new file mode 100644
index 0000000..f90d99c
--- /dev/null
+++ b/src/trame_server/mcp/protocol.py
@@ -0,0 +1,552 @@
+"""MCP JSON-RPC method dispatch (transport-independent).
+
+Clients of both eras are served, as MCP 2026-07-28 lets a server do. A
+request that names its protocol version in ``_meta`` comes from a client of
+2026-07-28 or later: it carries everything needed to serve it, and its
+result says so (``resultType``, the server's identity, caching hints). A
+client that opens with ``initialize`` speaks an earlier revision and is
+served as that revision says.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import contextlib
+import inspect
+import logging
+import re
+
+from trame_server.mcp import call_log, progress
+from trame_server.mcp.content import (
+ to_error_result,
+ to_prompt_messages,
+ to_resource_contents,
+ to_tool_result,
+)
+from trame_server.mcp.schema import ToolError, ValidationError, bind_arguments
+
+logger = logging.getLogger("trame_server.mcp")
+
+__all__ = ["MCPProtocol"]
+
+# 2026-07-28 and later: every request names its version and the client's
+# capabilities in _meta, and there is no handshake
+MODERN_VERSIONS = ("2026-07-28",)
+# Earlier revisions open with an initialize handshake, which negotiates one
+# of these (the first is preferred); still served for clients that have not
+# moved on
+LEGACY_VERSIONS = ("2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05")
+PROTOCOL_VERSIONS = MODERN_VERSIONS + LEGACY_VERSIONS
+
+# Reserved _meta keys
+VERSION_KEY = "io.modelcontextprotocol/protocolVersion"
+CAPABILITIES_KEY = "io.modelcontextprotocol/clientCapabilities"
+CLIENT_INFO_KEY = "io.modelcontextprotocol/clientInfo"
+SERVER_INFO_KEY = "io.modelcontextprotocol/serverInfo"
+
+# The results that carry caching hints (2026-07-28)
+CACHEABLE = frozenset(
+ (
+ "server/discover",
+ "tools/list",
+ "prompts/list",
+ "resources/list",
+ "resources/templates/list",
+ "resources/read",
+ )
+)
+
+# JSON-RPC error codes
+PARSE_ERROR = -32700
+INVALID_REQUEST = -32600
+METHOD_NOT_FOUND = -32601
+INVALID_PARAMS = -32602
+INTERNAL_ERROR = -32603
+# MCP's own (2026-07-28)
+HEADER_MISMATCH = -32020
+UNSUPPORTED_VERSION = -32022
+# The reply to a request the client cancelled (LSP's code; MCP defines none).
+# The client ignores it, but an HTTP POST has to end with something.
+REQUEST_CANCELLED = -32800
+
+
+class _InvalidParams(ValueError):
+ pass
+
+
+class _RequestCancelled(Exception):
+ pass
+
+
+def _optional(**fields):
+ """``fields`` without those that are None or empty, for a message's optional
+ fields."""
+ return {key: value for key, value in fields.items() if value}
+
+
+def _error(rpc_id, code, message, data=None):
+ error = {"code": code, "message": message}
+ if data is not None:
+ error["data"] = data
+ return {"jsonrpc": "2.0", "id": rpc_id, "error": error}
+
+
+def _result(rpc_id, payload):
+ return {"jsonrpc": "2.0", "id": rpc_id, "result": payload}
+
+
+async def _call(fn, arguments):
+ value = fn(**arguments)
+ if inspect.isawaitable(value):
+ value = await value
+ return value
+
+
+def _meta(params):
+ """A request's ``_meta``, or an empty dict."""
+ meta = params.get("_meta") if isinstance(params, dict) else None
+ return meta if isinstance(meta, dict) else {}
+
+
+def request_version(message):
+ """The protocol version a request names in its ``_meta``, as clients of
+ 2026-07-28 and later do; None for a client of an earlier revision."""
+ return _meta(message.get("params")).get(VERSION_KEY)
+
+
+def _caller(message, session):
+ """Who is asking, for the call log: the start of an HTTP session id,
+ else the name the client gives, kept to a few safe characters."""
+ if isinstance(session, str):
+ return session[:6]
+ info = _meta(message.get("params")).get(CLIENT_INFO_KEY)
+ name = info.get("name") if isinstance(info, dict) else None
+ if not isinstance(name, str):
+ return None
+ return re.sub(r"[^A-Za-z0-9_.-]", "_", name)[:24] or None
+
+
+def _reporter(params, notify):
+ """The progress reporter of a request asking for progress, when its
+ transport can notify; None otherwise."""
+ token = _meta(params).get("progressToken")
+ if notify is None or isinstance(token, bool) or not isinstance(token, (str, int)):
+ return None
+
+ async def send(fields):
+ await notify(
+ {
+ "jsonrpc": "2.0",
+ "method": "notifications/progress",
+ "params": {"progressToken": token, **fields},
+ }
+ )
+
+ return progress.Reporter(send)
+
+
+def check_request(message):
+ """The error that a request naming its version gets before it is handled (an
+ unsupported version, or missing client capabilities), or None. The HTTP
+ endpoint answers these errors with 400."""
+ rpc_id = message.get("id")
+ version = request_version(message)
+ if version not in MODERN_VERSIONS:
+ hint = " (it opens with initialize)" if version in LEGACY_VERSIONS else ""
+ return _error(
+ rpc_id,
+ UNSUPPORTED_VERSION,
+ f"Unsupported protocol version: {version!r}{hint}",
+ {"supported": list(PROTOCOL_VERSIONS), "requested": version},
+ )
+ if not isinstance(message["params"]["_meta"].get(CAPABILITIES_KEY), dict):
+ return _error(rpc_id, INVALID_PARAMS, f"_meta must carry {CAPABILITIES_KEY}")
+ return None
+
+
+def _describe_failure(name, error):
+ """Log a tool's exception, and return the text the agent reads. Expected
+ failures are logged at DEBUG, the others as errors with their traceback."""
+ if isinstance(error, (ValueError, LookupError, PermissionError)):
+ # Expected, actionable failures (bad input, unknown target, ...)
+ logger.debug("Tool %s failed: %s", name, error)
+ if isinstance(error, (ToolError, PermissionError)):
+ return str(error)
+ else:
+ logger.error("Tool %s raised", name, exc_info=error)
+ return f"{type(error).__name__}: {error}"
+
+
+class MCPProtocol:
+ """Dispatches MCP JSON-RPC messages against an ``MCP`` instance's registries."""
+
+ def __init__(self, mcp):
+ self._mcp = mcp
+ self._call_lock = asyncio.Lock()
+ # (session, request id) -> task of a request still running, and the
+ # tasks cancelled by the client -> its reason
+ self._in_flight = {}
+ self._cancelled = {}
+ served = {
+ "tools/list": self._on_tools_list,
+ "tools/call": self._on_tools_call,
+ "resources/list": self._on_resources_list,
+ "resources/templates/list": self._on_resource_templates_list,
+ "resources/read": self._on_resources_read,
+ "prompts/list": self._on_prompts_list,
+ "prompts/get": self._on_prompts_get,
+ }
+ self._modern_handlers = {"server/discover": self._on_discover, **served}
+ self._legacy_handlers = {
+ "initialize": self._on_initialize,
+ "ping": self._on_ping,
+ **served,
+ }
+
+ async def handle(self, message: dict, *, session=None, notify=None) -> dict | None:
+ """Handle one JSON-RPC message. Returns a response dict, or None for
+ notifications and responses, which expect no reply.
+
+ ``session`` scopes request ids, so that ``notifications/cancelled`` only
+ reaches the requests of the client that sent it. The HTTP endpoint passes
+ the ``Mcp-Session-Id`` header of clients older than 2026-07-28, and an
+ in-process client passes itself. A request the client cancels is answered
+ with a ``REQUEST_CANCELLED`` error, which the client ignores.
+
+ ``notify``, an async callable, sends the client a notification about this
+ request before the response; the transport passes one when it can send
+ notifications. With it, a request asking for progress (a
+ ``progressToken`` in its ``_meta``) gets the progress its tool or method
+ reports.
+ """
+ if not isinstance(message, dict) or message.get("jsonrpc") != "2.0":
+ return _error(None, INVALID_REQUEST, "Invalid JSON-RPC 2.0 message")
+
+ method = message.get("method")
+ rpc_id = message.get("id")
+
+ if method is None:
+ # A response from the client to a server request needs nothing more.
+ return None
+ if not isinstance(method, str):
+ return _error(rpc_id, INVALID_REQUEST, "Invalid method")
+
+ # The calls made while handling it know who asked (the call log)
+ with call_log.request(_caller(message, session)):
+ return await self._dispatch(message, method, rpc_id, session, notify)
+
+ async def _dispatch(self, message, method, rpc_id, session, notify):
+ if method.startswith("notifications/"):
+ if method == "notifications/cancelled":
+ params = message.get("params")
+ if isinstance(params, dict):
+ self.cancel(
+ params.get("requestId"),
+ session=session,
+ reason=params.get("reason"),
+ )
+ return None
+
+ modern = request_version(message) is not None
+ if modern:
+ rejection = check_request(message)
+ if rejection is not None:
+ return rejection
+ handler = self._handler(method, modern)
+ if handler is None:
+ return _error(rpc_id, METHOD_NOT_FOUND, f"Method not found: {method}")
+
+ params = message.get("params") or {}
+ if not isinstance(params, dict):
+ return _error(rpc_id, INVALID_PARAMS, "params must be an object")
+
+ reporter = _reporter(params, notify)
+ try:
+ with progress.reporting(reporter):
+ payload = handler(params)
+ if inspect.isawaitable(payload):
+ payload = await self._run_cancellable(payload, (session, rpc_id))
+ except _RequestCancelled as e:
+ return _error(rpc_id, REQUEST_CANCELLED, str(e))
+ except _InvalidParams as e:
+ return _error(rpc_id, INVALID_PARAMS, str(e))
+ except PermissionError as e:
+ return _error(rpc_id, INVALID_REQUEST, str(e))
+ except Exception as e:
+ logger.exception("Internal error handling %s", method)
+ return _error(rpc_id, INTERNAL_ERROR, f"{type(e).__name__}: {e}")
+ finally:
+ if reporter is not None:
+ await reporter.close() # nothing is sent after the response
+
+ if modern:
+ payload = self._complete(method, payload)
+ return _result(rpc_id, payload)
+
+ def _handler(self, method, modern):
+ handlers = self._modern_handlers if modern else self._legacy_handlers
+ return handlers.get(method)
+
+ def handles(self, message) -> bool:
+ """Whether a request's method is served, in its client's revision."""
+ return (
+ self._handler(message.get("method"), request_version(message) is not None)
+ is not None
+ )
+
+ def _complete(self, method, payload):
+ """A result as 2026-07-28 shapes it."""
+ result = {"resultType": "complete", **payload}
+ result["_meta"] = {
+ **(payload.get("_meta") or {}),
+ SERVER_INFO_KEY: self._info(),
+ }
+ if method in CACHEABLE:
+ # What it lists changes as the app runs, with no notification
+ # sent, and describes one app's live state
+ result["ttlMs"] = 0
+ result["cacheScope"] = "private"
+ return result
+
+ def _info(self):
+ from trame_server import __version__ # noqa: PLC0415
+
+ return {"name": self._mcp.name, "version": __version__}
+
+ # -------------------------------------------------------------------------
+ # Cancellation
+ # -------------------------------------------------------------------------
+
+ def cancel(self, request_id, *, session=None, reason=None) -> bool:
+ """Cancel the running request ``request_id`` of ``session``, as
+ ``notifications/cancelled`` does. Returns whether one was running.
+
+ The request's task is cancelled: its tool stops at its next
+ ``await`` (a synchronous tool has finished before any cancel can
+ arrive), releasing the call lock and flushing the state it changed.
+ """
+ try:
+ task = self._in_flight.get((session, request_id))
+ except TypeError: # an unhashable id: no request has it
+ return False
+ if task is None or task.done():
+ return False
+ logger.info(
+ "Request %r cancelled by the client: %s", request_id, reason or "no reason"
+ )
+ self._cancelled[task] = reason
+ task.cancel()
+ return True
+
+ async def _run_cancellable(self, awaitable, key):
+ """Await ``awaitable`` as a task that ``cancel(key)`` can stop."""
+ task = asyncio.ensure_future(awaitable)
+ try:
+ registered = self._in_flight.setdefault(key, task) is task
+ except TypeError:
+ registered = False
+ try:
+ return await task
+ except asyncio.CancelledError:
+ current = asyncio.current_task()
+ # Task.cancelling() is Python 3.11+; on 3.10, assume not
+ outer_cancelled = (
+ hasattr(current, "cancelling") and current.cancelling() > 0
+ )
+ if task not in self._cancelled or outer_cancelled:
+ raise # cancelled from the outside, e.g. the client disconnected
+ reason = self._cancelled[task]
+ msg = f"Request cancelled: {reason}" if reason else "Request cancelled"
+ raise _RequestCancelled(msg) from None
+ finally:
+ self._cancelled.pop(task, None)
+ if registered and self._in_flight.get(key) is task:
+ del self._in_flight[key]
+
+ # -------------------------------------------------------------------------
+ # Lifecycle
+ # -------------------------------------------------------------------------
+
+ def _on_discover(self, _params):
+ return {
+ "supportedVersions": list(PROTOCOL_VERSIONS),
+ "capabilities": {"tools": {}, "resources": {}, "prompts": {}},
+ "instructions": self._mcp._agent_instructions(),
+ }
+
+ def _on_initialize(self, params):
+ """The handshake of clients before 2026-07-28."""
+ requested = params.get("protocolVersion")
+ version = requested if requested in LEGACY_VERSIONS else LEGACY_VERSIONS[0]
+ payload = {
+ "protocolVersion": version,
+ "capabilities": {
+ "tools": {"listChanged": False},
+ "resources": {"listChanged": False},
+ "prompts": {"listChanged": False},
+ },
+ "serverInfo": self._info(),
+ }
+ payload["instructions"] = self._mcp._agent_instructions()
+ return payload
+
+ def _on_ping(self, _params):
+ return {}
+
+ # -------------------------------------------------------------------------
+ # Tools
+ # -------------------------------------------------------------------------
+
+ def _on_tools_list(self, _params):
+ tools = []
+ for entry in self._mcp.list_tools():
+ descriptor = {
+ "name": entry.name,
+ "description": entry.description,
+ "inputSchema": self._mcp._input_schema(entry),
+ }
+ if entry.annotations:
+ descriptor["annotations"] = entry.annotations
+ tools.append(descriptor)
+ return {"tools": tools}
+
+ async def _on_tools_call(self, params):
+ name = params.get("name")
+ entry = self._mcp.get_tool(name) if isinstance(name, str) else None
+ if entry is None:
+ msg = f"Unknown tool: {name}"
+ with call_log.logged("tool", str(name), params.get("arguments")):
+ raise _InvalidParams(msg)
+
+ try:
+ value = await self._execute(entry, params.get("arguments"))
+ except Exception as e:
+ return to_error_result(_describe_failure(name, e))
+
+ return to_tool_result(value, structured=self._mcp.structured_content)
+
+ async def _execute(self, entry, arguments):
+ """Run a tool entry. Access, permissions and arguments are checked first, then
+ the call runs, one at a time unless it may run concurrently.
+
+ Returns the tool's raw value; raises on failure.
+ """
+ with call_log.logged("tool", entry.name, arguments):
+ self._mcp._check_enabled()
+ self._mcp.permissions.require(*entry.requires, what=entry.name)
+ try:
+ arguments = bind_arguments(
+ entry.fn, arguments, self._mcp._input_schema(entry)
+ )
+ except ValidationError as e:
+ msg = f"Invalid arguments for tool {entry.name}: {e}"
+ raise ValidationError(msg) from None
+
+ async with self.locked(entry.concurrent):
+ # Ids given for object-typed parameters become objects here,
+ # under the lock, where the graph is as earlier calls left it.
+ arguments = self._mcp._objects.resolve_arguments(
+ entry.fn,
+ arguments,
+ read_only=bool((entry.annotations or {}).get("readOnlyHint")),
+ )
+ arguments = progress.inject(entry.fn, arguments)
+ result = await self._call_flushing(entry.fn, arguments)
+ if entry.input_schema is None: # the app's own tool
+ result = self._mcp._objects.encode_tool_result(result)
+ return result
+
+ @contextlib.asynccontextmanager
+ async def locked(self, concurrent=False):
+ """Hold the call lock for the block, so that agent calls run one at a time.
+ Nothing is held when the call is ``concurrent``, or when every call may be
+ (``concurrent_calls``).
+
+ ``object_call`` runs unlocked and takes the lock here itself, so the
+ called method's own ``concurrent`` option decides.
+ """
+ if not (concurrent or self._mcp.concurrent_calls):
+ async with self._call_lock:
+ yield
+ else:
+ yield
+
+ async def _call_flushing(self, fn, arguments):
+ # trame pushes state changes and runs @state.change reactions on a
+ # flush, which an HTTP request never triggers by itself: without one,
+ # what a tool assigns would wait for some unrelated flush.
+ with self._mcp.server.state:
+ return await _call(fn, arguments)
+
+ # -------------------------------------------------------------------------
+ # Resources
+ # -------------------------------------------------------------------------
+
+ def _on_resources_list(self, _params):
+ return {
+ "resources": [
+ {
+ "uri": entry.uri,
+ "name": entry.name,
+ **_optional(
+ description=entry.description, mimeType=entry.mime_type
+ ),
+ }
+ for entry in self._mcp.list_resources()
+ ]
+ }
+
+ def _on_resource_templates_list(self, _params):
+ return {"resourceTemplates": []}
+
+ async def _on_resources_read(self, params):
+ uri = params.get("uri")
+ entry = self._mcp.get_resource(uri) if isinstance(uri, str) else None
+ if entry is None:
+ msg = f"Unknown resource: {uri}"
+ with call_log.logged("resource", str(uri)):
+ raise _InvalidParams(msg)
+
+ with call_log.logged("resource", entry.uri):
+ self._mcp._check_enabled()
+ value = await _call(entry.fn, {})
+ return to_resource_contents(entry.uri, value, entry.mime_type)
+
+ # -------------------------------------------------------------------------
+ # Prompts
+ # -------------------------------------------------------------------------
+
+ def _on_prompts_list(self, _params):
+ return {
+ "prompts": [
+ {
+ "name": entry.name,
+ **_optional(description=entry.description),
+ "arguments": entry.arguments,
+ }
+ for entry in self._mcp.list_prompts()
+ ]
+ }
+
+ async def _on_prompts_get(self, params):
+ name = params.get("name")
+ entry = self._mcp.get_prompt(name) if isinstance(name, str) else None
+ if entry is None:
+ msg = f"Unknown prompt: {name}"
+ with call_log.logged("prompt", str(name), params.get("arguments")):
+ raise _InvalidParams(msg)
+
+ arguments = params.get("arguments") or {}
+ with call_log.logged("prompt", name, arguments):
+ self._mcp._check_enabled()
+ try:
+ inspect.signature(entry.fn).bind(**arguments)
+ except TypeError as e:
+ msg = f"Invalid arguments for prompt {name}: {e}"
+ raise _InvalidParams(msg) from None
+
+ value = await _call(entry.fn, arguments)
+ return {
+ **_optional(description=entry.description),
+ "messages": to_prompt_messages(value),
+ }
diff --git a/src/trame_server/mcp/schema.py b/src/trame_server/mcp/schema.py
new file mode 100644
index 0000000..6c2d113
--- /dev/null
+++ b/src/trame_server/mcp/schema.py
@@ -0,0 +1,644 @@
+"""JSON Schema generation from Python type annotations, and validation of
+incoming MCP values against the schemas we advertise."""
+
+from __future__ import annotations
+
+import inspect
+import json
+import re
+import types
+import typing
+
+from trame_common.obj.mcp import MCPExposable, Progress
+
+__all__ = [
+ "ToolError",
+ "ValidationError",
+ "bind_arguments",
+ "docstring",
+ "error_text",
+ "from_json",
+ "function_input_schema",
+ "is_object",
+ "object_class",
+ "parameter_hints",
+ "resolve_object_arguments",
+ "return_hint",
+ "type_to_schema",
+ "unwrap",
+ "validate",
+]
+
+_SCALARS = {
+ str: {"type": "string"},
+ int: {"type": "integer"},
+ float: {"type": "number"},
+ bool: {"type": "boolean"},
+ type(None): {"type": "null"},
+}
+
+
+def type_to_schema(annotation, custom=None) -> dict:
+ """Best-effort conversion of a type annotation to a JSON Schema fragment.
+
+ Unknown or missing annotations yield ``{}`` (any type). ``custom`` is an
+ optional ``annotation -> schema | None`` hook consulted first at every
+ level (used to describe references to components and models).
+
+ ``Annotated`` metadata contributes a description (``str``) or extra
+ schema keywords (``dict``), e.g.
+ ``Annotated[int, "Number of facets", {"minimum": 3, "maximum": 60}]``.
+ """
+ if annotation is None or annotation is inspect.Parameter.empty:
+ return {}
+
+ if custom is not None:
+ schema = custom(annotation)
+ if schema is not None:
+ return schema
+
+ # isinstance first: Annotated metadata may be unhashable (dict schemas)
+ if isinstance(annotation, type) and annotation in _SCALARS:
+ return dict(_SCALARS[annotation])
+
+ origin = typing.get_origin(annotation)
+ args = typing.get_args(annotation)
+
+ def convert(a):
+ return type_to_schema(a, custom)
+
+ if origin is None:
+ if annotation is dict:
+ return {"type": "object"}
+ if annotation in (list, set, frozenset, tuple):
+ return {"type": "array"}
+ return {}
+
+ if origin is typing.Annotated:
+ schema = convert(args[0])
+ for extra in args[1:]:
+ if isinstance(extra, str):
+ schema["description"] = extra
+ elif isinstance(extra, dict):
+ schema.update(extra)
+ return schema
+
+ if origin is typing.Literal:
+ return {"enum": list(args)}
+
+ if origin in (typing.Union, types.UnionType):
+ non_none = [a for a in args if a is not type(None)]
+ optional = len(non_none) != len(args)
+ if len(non_none) == 1:
+ schema = convert(non_none[0])
+ return nullable(schema) if optional else schema
+ variants = [convert(a) for a in non_none]
+ if optional:
+ variants.append({"type": "null"})
+ return {"anyOf": variants}
+
+ if origin is tuple and not (len(args) == 2 and args[1] is Ellipsis):
+ # Fixed-length tuple, e.g. tuple[float, float, float]
+ items = [convert(a) for a in args]
+ schema = {"type": "array", "minItems": len(items), "maxItems": len(items)}
+ if items and all(item == items[0] for item in items):
+ schema["items"] = items[0]
+ elif items:
+ schema["prefixItems"] = items
+ return schema
+
+ if origin in (list, set, frozenset, tuple):
+ return {"type": "array", "items": convert(args[0]) if args else {}}
+
+ if origin is dict:
+ value_schema = convert(args[1]) if len(args) == 2 else {}
+ return {"type": "object", "additionalProperties": value_schema}
+
+ return {}
+
+
+_ARRAYS = (list, tuple, set, frozenset)
+
+
+def from_json(value, annotation, resolve=None, path="value"):
+ """
+ ``value``, validated JSON, in the Python shape ``annotation`` declares.
+ JSON has no tuples or sets, so arrays become tuples or sets where the
+ annotation says so (``tuple[float, float, float]``, ``set[str]``), nested
+ in lists, dicts and unions too. Anything else is returned as is.
+
+ With ``resolve``, an id or name given where the annotation names a class
+ whose instances agents reach becomes the object: ``resolve(id, cls,
+ path)`` returns it or raises. Converting a value twice gives the same
+ value, so ids can be resolved after the shape is restored.
+ """
+ if value is None or annotation is None or annotation is inspect.Parameter.empty:
+ return value
+ if resolve is not None:
+ cls = object_class(annotation)
+ if cls is not None:
+ return resolve(value, cls, path) if isinstance(value, str) else value
+ origin = typing.get_origin(annotation)
+ args = typing.get_args(annotation)
+ if origin is typing.Annotated:
+ return from_json(value, args[0], resolve, path)
+ if origin in (typing.Union, types.UnionType):
+ for arg in args:
+ base = (
+ typing.get_args(arg)[0]
+ if typing.get_origin(arg) is typing.Annotated
+ else arg
+ )
+ container = typing.get_origin(base) or base
+ if isinstance(value, str):
+ if resolve is not None and object_class(base) is not None:
+ return resolve(value, base, path)
+ elif isinstance(value, dict):
+ if container is dict:
+ return from_json(value, base, resolve, path)
+ elif isinstance(value, _ARRAYS) and container in _ARRAYS:
+ return from_json(value, base, resolve, path)
+ return value
+ if isinstance(value, _ARRAYS):
+ if annotation in (tuple, set, frozenset):
+ return annotation(value)
+ if origin is tuple:
+ if len(args) == 2 and args[1] is Ellipsis:
+ args = (args[0],) * len(value)
+ if len(args) != len(value):
+ return tuple(value)
+ return tuple(
+ from_json(v, a, resolve, f"{path}[{i}]")
+ for i, (v, a) in enumerate(zip(value, args, strict=True))
+ )
+ if origin in (list, set, frozenset) and args:
+ items = [
+ from_json(v, args[0], resolve, f"{path}[{i}]")
+ for i, v in enumerate(value)
+ ]
+ return items if origin is list else origin(items)
+ if isinstance(value, dict) and origin is dict and len(args) == 2:
+ return {
+ k: from_json(v, args[1], resolve, f"{path}.{k}") for k, v in value.items()
+ }
+ return value
+
+
+def nullable(schema: dict) -> dict:
+ """Return ``schema`` extended to also accept ``null``."""
+ if not schema or _accepts_null(schema):
+ return schema
+ return {"anyOf": [schema, {"type": "null"}]}
+
+
+def _accepts_null(schema):
+ json_type = schema.get("type")
+ if json_type == "null" or (isinstance(json_type, list) and "null" in json_type):
+ return True
+ return any(_accepts_null(s) for s in schema.get("anyOf", ()))
+
+
+def parameter_hints(fn):
+ """The resolved annotations of ``fn``'s parameters. One annotation that
+ cannot be resolved (a forward reference to a later class, typically the
+ return type) does not lose the others."""
+ try:
+ return typing.get_type_hints(fn, include_extras=True)
+ except Exception:
+ pass
+ func = inspect.unwrap(getattr(fn, "__func__", fn))
+ globalns = getattr(func, "__globals__", {})
+ hints = {}
+ for name, annotation in getattr(func, "__annotations__", {}).items():
+ if name == "return":
+ continue
+ holder = types.SimpleNamespace(__annotations__={name: annotation})
+ try:
+ hints[name] = typing.get_type_hints(
+ holder, globalns=globalns, include_extras=True
+ )[name]
+ except Exception:
+ continue
+ return hints
+
+
+def is_progress(annotation) -> bool:
+ """True for ``Progress``, ``Progress | None`` and ``Optional[Progress]``
+ (Annotated or not): the parameter trame fills in with a reporter."""
+ if typing.get_origin(annotation) is typing.Annotated:
+ annotation = typing.get_args(annotation)[0]
+ if typing.get_origin(annotation) in (typing.Union, types.UnionType):
+ args = [a for a in typing.get_args(annotation) if a is not type(None)]
+ annotation = args[0] if len(args) == 1 else None
+ return isinstance(annotation, type) and issubclass(annotation, Progress)
+
+
+def progress_parameter(fn):
+ """The name of ``fn``'s ``Progress`` parameter, or None."""
+ for name, annotation in parameter_hints(fn).items():
+ if name != "return" and is_progress(annotation):
+ return name
+ return None
+
+
+def check_progress(fn, label):
+ """Raise when ``fn`` declares a ``Progress`` parameter but isn't async, since
+ reports are awaited."""
+ if progress_parameter(fn) is None or inspect.iscoroutinefunction(fn):
+ return
+ msg = f"{label}: a Progress parameter needs an async function (async def)"
+ raise TypeError(msg)
+
+
+def _json_safe(value):
+ try:
+ json.dumps(value)
+ except (TypeError, ValueError):
+ return False
+ return True
+
+
+def return_hint(fn):
+ """The resolved return annotation of ``fn``, or None."""
+ try:
+ return typing.get_type_hints(fn, include_extras=True).get("return")
+ except Exception:
+ return None
+
+
+# A line starting a list item or a field (":param x:"), which keeps its line
+# break; the lines indented under it continue it
+_ITEM = re.compile(r"\s*(?:[-*+•]|\d+[.)]|:[^:\s][^:]*:)\s")
+
+
+def unwrap(text):
+ """``text`` with the wrapped lines of each paragraph joined, as agents read
+ it best. Blank lines, list items, fields and indented blocks (code,
+ ``Args:`` sections) keep their line breaks, and so does what is between
+ ``` fences."""
+ if not text:
+ return text
+ lines = []
+ fenced = False
+ # What the next line may continue: top-level prose, or the item at
+ # this indent (by lines indented under it)
+ prose, item = False, None
+ for line in text.splitlines():
+ stripped = line.strip()
+ indent = len(line) - len(line.lstrip())
+ fence = stripped.startswith("```")
+ starts_item = _ITEM.match(line) is not None
+ if stripped and not (fenced or fence or starts_item):
+ if (item is not None and indent > item) or (prose and indent == 0):
+ lines[-1] = f"{lines[-1].rstrip()} {stripped}"
+ continue
+ lines.append(line)
+ fenced ^= fence
+ if fenced or fence or not stripped:
+ prose, item = False, None
+ elif starts_item:
+ prose, item = False, indent
+ else:
+ prose, item = indent == 0, None
+ return "\n".join(lines)
+
+
+def docstring(obj):
+ """``obj``'s docstring as agents read it (see :func:`unwrap`), or None."""
+ return unwrap(inspect.getdoc(obj))
+
+
+def function_input_schema(fn, skip=("self",), ref=None) -> dict:
+ """Build the MCP ``inputSchema`` for a callable from its signature.
+ ``ref`` describes parameters annotated with a component or model class,
+ which take the object's id or name (see ``type_to_schema``'s ``custom``). A
+ ``Progress`` parameter is trame's to fill in, so agents don't see it."""
+ sig = inspect.signature(fn)
+ hints = parameter_hints(fn)
+
+ properties = {}
+ required = []
+ var_keyword = False
+ for pname, param in sig.parameters.items():
+ if param.kind is inspect.Parameter.VAR_KEYWORD:
+ var_keyword = True
+ continue
+ if pname in skip or param.kind is inspect.Parameter.VAR_POSITIONAL:
+ continue
+ if is_progress(hints.get(pname)):
+ continue
+ prop = type_to_schema(hints.get(pname), ref)
+ if param.default is inspect.Parameter.empty:
+ required.append(pname)
+ else:
+ if param.default is None:
+ prop = nullable(prop)
+ if _json_safe(param.default):
+ prop["default"] = param.default
+ properties[pname] = prop
+
+ schema = {"type": "object", "properties": properties}
+ if required:
+ schema["required"] = required
+ if not var_keyword:
+ schema["additionalProperties"] = False
+ return schema
+
+
+# -----------------------------------------------------------------------------
+# Validation
+# -----------------------------------------------------------------------------
+
+
+class ToolError(ValueError):
+ """An expected, actionable failure whose message is complete as is: the
+ agent reads it without the exception's type name."""
+
+
+class ValidationError(ToolError):
+ """An MCP-supplied value does not match the advertised schema."""
+
+
+def error_text(error):
+ """The text agents read for a failure: the message of a ``ToolError`` or
+ ``PermissionError`` as is, else the exception's type and message."""
+ if isinstance(error, (ToolError, PermissionError)):
+ return str(error)
+ return f"{type(error).__name__}: {error}"
+
+
+def _type_name(value):
+ if value is None:
+ return "null"
+ if isinstance(value, bool):
+ return "boolean"
+ if isinstance(value, int):
+ return "integer"
+ if isinstance(value, float):
+ return "number"
+ if isinstance(value, str):
+ return "string"
+ if isinstance(value, (list, tuple)):
+ return "array"
+ if isinstance(value, dict):
+ return "object"
+ return type(value).__name__
+
+
+def _show(value):
+ """``value`` as JSON for a message, the way the agent wrote it."""
+ try:
+ return json.dumps(value)
+ except (TypeError, ValueError):
+ return repr(value)
+
+
+def _json_equal(a, b):
+ return a == b and isinstance(a, bool) == isinstance(b, bool)
+
+
+def _check_type(value, json_type, path):
+ """Return ``value`` coerced to ``json_type`` (lossless numeric coercion only)."""
+ is_number = isinstance(value, (int, float)) and not isinstance(value, bool)
+ if json_type == "integer":
+ if is_number and isinstance(value, int):
+ return value
+ if is_number and isinstance(value, float) and value.is_integer():
+ return int(value)
+ elif json_type == "number":
+ if is_number:
+ return float(value) if isinstance(value, int) else value
+ elif json_type == "string":
+ if isinstance(value, str):
+ return value
+ elif json_type == "boolean":
+ if isinstance(value, bool):
+ return value
+ elif json_type == "null":
+ if value is None:
+ return value
+ elif json_type == "array":
+ if isinstance(value, (list, tuple)):
+ return list(value)
+ elif json_type == "object":
+ if isinstance(value, dict):
+ return value
+ else:
+ return value # unknown type keyword: do not reject
+
+ msg = f"{path}: expected {json_type}, got {_type_name(value)}"
+ raise ValidationError(msg)
+
+
+def validate(value, schema, path="value"):
+ """Validate ``value`` against the JSON Schema subset trame generates.
+
+ Returns the value with lossless coercions applied (``3.0`` for an
+ integer becomes ``3``, ``3`` for a number becomes ``3.0``); raises
+ :class:`ValidationError` naming the offending path otherwise. Keywords
+ outside the supported subset are ignored.
+ """
+ if not schema:
+ return value
+
+ branches = schema.get("anyOf") or schema.get("oneOf")
+ if branches:
+ errors = []
+ # A branch of the value's own type first: 3 for float | int stays 3
+ exact = _type_name(value)
+ branches = sorted(branches, key=lambda b: b.get("type") != exact)
+ for branch in branches:
+ try:
+ value = validate(value, branch, path)
+ break
+ except ValidationError as e:
+ errors.append(str(e).removeprefix(f"{path}: "))
+ else:
+ msg = f"{path}: does not match any allowed form ({'; '.join(errors)})"
+ raise ValidationError(msg)
+
+ if "object" in schema and not isinstance(value, str):
+ msg = (
+ f"{path}: expected the id of an object of type {schema['object']}, "
+ f"got {_type_name(value)}"
+ )
+ raise ValidationError(msg)
+
+ json_type = schema.get("type")
+ if isinstance(json_type, list):
+ for candidate in sorted(json_type, key=lambda k: k != _type_name(value)):
+ try:
+ value = _check_type(value, candidate, path)
+ break
+ except ValidationError:
+ continue
+ else:
+ msg = f"{path}: expected {' or '.join(json_type)}, got {_type_name(value)}"
+ raise ValidationError(msg)
+ elif json_type is not None:
+ value = _check_type(value, json_type, path)
+
+ if "const" in schema and not _json_equal(value, schema["const"]):
+ msg = f"{path}: must be {_show(schema['const'])}"
+ raise ValidationError(msg)
+ if "enum" in schema and not any(_json_equal(value, e) for e in schema["enum"]):
+ choices = ", ".join(_show(e) for e in schema["enum"])
+ msg = f"{path}: must be one of {choices}, got {_show(value)}"
+ raise ValidationError(msg)
+
+ if isinstance(value, (int, float)) and not isinstance(value, bool):
+ _check_bounds(value, schema, path)
+ elif isinstance(value, str):
+ _check_string(value, schema, path)
+ elif isinstance(value, list):
+ value = _check_array(value, schema, path)
+ elif isinstance(value, dict):
+ value = _check_object(value, schema, path)
+
+ return value
+
+
+def _check_bounds(value, schema, path):
+ checks = (
+ ("minimum", lambda v, b: v >= b, "at least"),
+ ("maximum", lambda v, b: v <= b, "at most"),
+ ("exclusiveMinimum", lambda v, b: v > b, "greater than"),
+ ("exclusiveMaximum", lambda v, b: v < b, "less than"),
+ )
+ for keyword, ok, label in checks:
+ if keyword in schema and not ok(value, schema[keyword]):
+ msg = f"{path}: must be {label} {schema[keyword]}, got {value}"
+ raise ValidationError(msg)
+
+
+def _check_string(value, schema, path):
+ if "minLength" in schema and len(value) < schema["minLength"]:
+ msg = f"{path}: must be at least {schema['minLength']} characters"
+ raise ValidationError(msg)
+ if "maxLength" in schema and len(value) > schema["maxLength"]:
+ msg = f"{path}: must be at most {schema['maxLength']} characters"
+ raise ValidationError(msg)
+ if "pattern" in schema and not re.search(schema["pattern"], value):
+ msg = f"{path}: must match pattern {schema['pattern']!r}"
+ raise ValidationError(msg)
+
+
+def _check_array(value, schema, path):
+ if "minItems" in schema and len(value) < schema["minItems"]:
+ msg = f"{path}: expected at least {schema['minItems']} items, got {len(value)}"
+ raise ValidationError(msg)
+ if "maxItems" in schema and len(value) > schema["maxItems"]:
+ msg = f"{path}: expected at most {schema['maxItems']} items, got {len(value)}"
+ raise ValidationError(msg)
+
+ prefix = schema.get("prefixItems", ())
+ items = schema.get("items")
+ result = []
+ for i, item in enumerate(value):
+ item_schema = prefix[i] if i < len(prefix) else items
+ result.append(
+ validate(item, item_schema, f"{path}[{i}]") if item_schema else item
+ )
+ return result
+
+
+def _check_object(value, schema, path):
+ properties = schema.get("properties", {})
+ additional = schema.get("additionalProperties", True)
+
+ missing = [k for k in schema.get("required", ()) if k not in value]
+ if missing:
+ msg = f"{path}: missing required {', '.join(repr(k) for k in missing)}"
+ raise ValidationError(msg)
+
+ result = {}
+ for key, item in value.items():
+ if not isinstance(key, str):
+ msg = f"{path}: keys must be strings"
+ raise ValidationError(msg)
+ if key in properties:
+ result[key] = validate(item, properties[key], f"{path}.{key}")
+ elif additional is False:
+ msg = f"{path}: unexpected {key!r}" + (
+ f" (allowed: {sorted(properties)})" if properties else ""
+ )
+ raise ValidationError(msg)
+ elif isinstance(additional, dict):
+ result[key] = validate(item, additional, f"{path}.{key}")
+ else:
+ result[key] = item
+ return result
+
+
+def bind_arguments(fn, arguments, schema, label="arguments", positional=()):
+ """Validate MCP call arguments for ``fn`` and return the coerced dict.
+
+ Checks them against ``schema`` and against ``fn``'s signature (catching
+ missing/unexpected arguments the schema may not describe), so that a
+ ``TypeError`` raised later can only come from the function body.
+ ``positional`` are the leading arguments the caller supplies itself
+ (a constructor's server). Object-typed parameters keep the ids or
+ names given; see :func:`resolve_object_arguments`.
+ """
+ if arguments is None:
+ arguments = {}
+ if not isinstance(arguments, dict):
+ msg = f"{label}: expected object, got {_type_name(arguments)}"
+ raise ValidationError(msg)
+ arguments = validate(arguments, schema, label)
+ # The Progress parameter is filled in later (see progress.inject)
+ reporter = progress_parameter(fn)
+ filled = {reporter: None} if reporter and reporter not in arguments else {}
+ try:
+ inspect.signature(fn).bind(*positional, **arguments, **filled)
+ except TypeError as e:
+ msg = f"{label}: {e}"
+ raise ValidationError(msg) from None
+ hints = parameter_hints(fn)
+ return {
+ name: from_json(value, hints.get(name)) for name, value in arguments.items()
+ }
+
+
+def is_object(value) -> bool:
+ """Whether ``value`` is an object agents may reach, once its class declares
+ something: an instance of a class that inherits ``MCPExposable``, such as
+ a component or a trame-dataclass model."""
+ return isinstance(value, MCPExposable)
+
+
+def object_class(annotation):
+ """``annotation`` when it is a class whose instances agents may reach,
+ else None."""
+ if isinstance(annotation, type) and issubclass(annotation, MCPExposable):
+ return annotation
+ return None
+
+
+def object_classes(annotation) -> set:
+ """The component and model classes named anywhere in ``annotation``."""
+ found, stack = set(), [annotation]
+ while stack:
+ current = stack.pop()
+ cls = object_class(current)
+ if cls is not None:
+ found.add(cls)
+ else:
+ stack.extend(typing.get_args(current))
+ return found
+
+
+def resolve_object_arguments(fn, arguments, resolve, label="arguments"):
+ """``arguments`` (bound by :func:`bind_arguments`) with the ids or names given
+ for object-typed parameters replaced by the objects:
+ ``resolve(id, cls, path)`` returns the object or raises."""
+ hints = parameter_hints(fn)
+ typed = {name for name, hint in hints.items() if object_classes(hint)}
+ if not typed & arguments.keys():
+ return arguments
+ return {
+ name: from_json(value, hints[name], resolve, f"{label}.{name}")
+ if name in typed
+ else value
+ for name, value in arguments.items()
+ }
diff --git a/src/trame_server/mcp/typeinfo.py b/src/trame_server/mcp/typeinfo.py
new file mode 100644
index 0000000..51faaf7
--- /dev/null
+++ b/src/trame_server/mcp/typeinfo.py
@@ -0,0 +1,448 @@
+"""What agents see of a class: its properties, methods and constructor.
+
+trame-common and trame-dataclass only store what a class declares, as plain
+data (``Cls.mcp_describe()``); this module interprets it. A class is visible
+when a keyword or ``mcp_describe()`` declares it, or when it has markers
+(``@mcp.method``, ``@mcp.property``), an exposed field or a constructor,
+unless it is hidden with False. Fields and constructors come from the
+class's ``MCPExposable`` hooks (``_mcp_fields``, ``_mcp_constructor``),
+which apply the rules of its type of class, such as a model's
+``all_fields``.
+"""
+
+from __future__ import annotations
+
+import inspect
+import logging
+import typing
+import weakref
+from dataclasses import dataclass, field
+
+from trame_common.obj import mcp as declarations
+from trame_common.obj.mcp import METHOD_MARKER, PROPERTY_MARKER
+
+from trame_server.mcp.schema import (
+ check_progress,
+ docstring,
+ nullable,
+ object_class,
+ object_classes,
+ return_hint,
+ type_to_schema,
+ unwrap,
+)
+
+logger = logging.getLogger("trame_server.mcp")
+
+__all__ = [
+ "Constructor",
+ "Method",
+ "Property",
+ "TypeInfo",
+ "is_visible",
+ "property_schema",
+ "reference_schema",
+ "tool_reference_schema",
+ "type_info",
+ "type_name",
+ "type_names",
+]
+
+STATE_TYPE = "State"
+
+
+# Methods trame calls back on its own (@change, @trigger, @controller, @watch)
+_CALLBACK_MARKERS = (
+ "_trame_state_change",
+ "_trame_trigger_names",
+ "_trame_controller",
+ "_watch",
+)
+
+
+@dataclass(frozen=True)
+class Property:
+ name: str
+ origin: str # "field" (_mcp_fields), "property" (Python) or "state" (key)
+ schema: dict # what is written (objects by id), without its description
+ description: str | None = None
+ writable: bool = False # can be written, permissions aside
+ requires: tuple = () # to read it at all
+ set_requires: tuple = () # to write it, in addition
+ reference: bool = False # may hold objects agents reach
+ type_def: object = None # the declared type (tuples, objects by id)
+
+ def described(self) -> dict:
+ """The schema with the description, as agents read it."""
+ if not self.description:
+ return dict(self.schema)
+ return {**self.schema, "description": self.description}
+
+
+@dataclass(frozen=True)
+class Method:
+ name: str # the name agents call it by
+ attr: str
+ description: str
+ read_only: bool = False
+ annotations: dict | None = None # MCP tool annotations, but readOnlyHint
+ concurrent: bool = False
+ requires: tuple = ()
+
+
+@dataclass(frozen=True)
+class Constructor:
+ attr: str | None # the classmethod, or None for cls(server, **values)
+ description: str = ""
+ requires: tuple = ()
+ server: str | None = None # the classmethod's parameter taking the server
+
+
+@dataclass(frozen=True)
+class TypeInfo:
+ cls: type | None # None for the state object
+ visible: bool
+ description: str | None = None
+ properties: dict = field(default_factory=dict)
+ methods: dict = field(default_factory=dict)
+ constructor: Constructor | None = None
+ # Why the class's constructor cannot work, warned about when described
+ constructor_warning: str | None = None
+ # Reference fields left hidden, name -> classes they hold (startup audit)
+ hidden_references: dict = field(default_factory=dict)
+
+
+HIDDEN = TypeInfo(cls=None, visible=False)
+
+# Cached on the class itself (its own __dict__, never inherited): a
+# TypeInfo refers to its class, which a WeakKeyDictionary would keep alive
+_CACHE_ATTR = "_trame_mcp_type_info"
+_VISIBLE = weakref.WeakKeyDictionary() # cls -> (version, bool)
+
+
+def type_info(cls) -> TypeInfo:
+ """What agents see of ``cls`` (cached until a class declares or is
+ described again)."""
+ version = declarations.options_version()
+ cached = vars(cls).get(_CACHE_ATTR)
+ if cached is not None and cached[0] == version:
+ return cached[1]
+ info = _build(cls) if is_visible(cls) else HIDDEN
+ setattr(cls, _CACHE_ATTR, (version, info))
+ return info
+
+
+def is_visible(cls) -> bool:
+ """Whether agents may see ``cls``, a component, model or other ``MCPExposable``
+ class."""
+ if not isinstance(cls, type):
+ return False
+ version = declarations.options_version()
+ cached = _VISIBLE.get(cls)
+ if cached is not None and cached[0] == version:
+ return cached[1]
+ visible = _declares(cls)
+ _VISIBLE[cls] = (version, visible)
+ return visible
+
+
+def _declares(cls):
+ if object_class(cls) is None:
+ return False
+ declared = declarations.class_options(cls)["declared"]
+ if declared is not None:
+ return declared
+ # A field's mcp=True is an empty dict of options, which still exposes it
+ return (
+ declarations.has_markers(cls)
+ or any(isinstance(f.options, dict) for f in cls._mcp_fields().values())
+ or cls._mcp_constructor() is not None
+ )
+
+
+def _object_reference(annotation, describe):
+ """The schema of a value that holds an object of the class ``annotation``. It is
+ ``describe(name)`` for a visible class, and a plain string otherwise, since
+ agents cannot use the id. None when ``annotation`` names no such class."""
+ if typing.get_origin(annotation) is not None:
+ return None # on Python 3.10, isinstance(list[X], type) holds
+ cls = object_class(annotation)
+ if cls is None:
+ return None
+ if not is_visible(cls):
+ return {"type": "string"}
+ return describe(type_name(cls))
+
+
+def reference_schema(annotation):
+ """The ``type_to_schema`` hook that describes a value holding a component or
+ model as ``{"object": "T"}``, the same in properties, parameters and returns.
+ Agents read it as an ``{"id", "type"}`` reference, a method returns it as
+ object_get shows it, and agents write it by id (a parameter also takes an
+ object name). ``validate`` checks that it is a string."""
+ return _object_reference(annotation, lambda name: {"object": name})
+
+
+def tool_reference_schema(annotation):
+ """The ``type_to_schema`` hook for the input schema of an app's own tool, as
+ clients read it in ``tools/list``. An object parameter is a string, and its
+ description says what type of object it names."""
+ return _object_reference(
+ annotation,
+ lambda name: {"type": "string", "description": f"{name} object, by id or name"},
+ )
+
+
+# -----------------------------------------------------------------------------
+# Type names
+# -----------------------------------------------------------------------------
+
+_NAMES = {"version": None, "names": {}, "classes": {}}
+_WARNED = weakref.WeakSet()
+
+
+def type_names():
+ """``(names, classes)``: the agent-facing name of every visible class, and
+ the reverse. A class is named after itself; when an earlier visible class
+ already has that name, it gets its module-qualified name, with a
+ warning. ``State`` is the state object's."""
+ version = declarations.options_version()
+ if _NAMES["version"] == version:
+ return _NAMES["names"], _NAMES["classes"]
+
+ names, classes = weakref.WeakKeyDictionary(), weakref.WeakValueDictionary()
+ for cls in declarations.declared_classes():
+ if not is_visible(cls):
+ continue
+ name = cls.__name__
+ if name in classes or name == STATE_TYPE:
+ first = classes.get(name)
+ name = f"{cls.__module__}.{cls.__qualname__}"
+ if cls not in _WARNED:
+ _WARNED.add(cls)
+ logger.warning(
+ "Two classes agents see are named %s: %s keeps the name, %s is "
+ "called %s",
+ cls.__name__,
+ "the state object" if first is None else first.__qualname__,
+ cls.__qualname__,
+ name,
+ )
+ names[cls] = name
+ classes[name] = cls
+ _NAMES.update(version=version, names=names, classes=classes)
+ return names, classes
+
+
+def type_name(cls) -> str:
+ return type_names()[0].get(cls) or cls.__name__
+
+
+# -----------------------------------------------------------------------------
+# Building
+# -----------------------------------------------------------------------------
+
+
+def _members(cls):
+ """``{name: member}`` of ``cls`` and its bases, in definition order, a base's
+ members first. A member that a subclass overrides keeps the place where the
+ base defined it."""
+ members = {}
+ for klass in reversed(cls.__mro__):
+ members.update(vars(klass))
+ return members
+
+
+def _base_names(cls):
+ """The names of the members that trame's own base classes define. Those are the
+ classes from the packages that the classes in the MRO name in
+ ``_mcp_api_packages``. ``all_methods`` never exposes these members, and
+ marking or listing one is an error."""
+ packages = {"builtins"}
+ for klass in cls.__mro__:
+ packages.update(vars(klass).get("_mcp_api_packages", ()))
+ names = set()
+ for klass in cls.__mro__:
+ if klass.__module__.split(".")[0] in packages:
+ names.update(vars(klass))
+ return names
+
+
+def property_schema(annotation, options, *, ref=None, can_be_null=False):
+ """``(schema, description)`` of a property from its annotation and its
+ options. The options' ``schema`` keywords go over the annotation's
+ schema, which accepts null too with ``can_be_null``. The description is
+ the options' own, else the annotation's (``Annotated[T, "..."]``), and
+ never stays in the schema."""
+ schema = type_to_schema(annotation, ref)
+ schema.update(options.get("schema") or {})
+ found = schema.pop("description", None)
+ if can_be_null:
+ schema = nullable(schema)
+ return schema, options.get("description") or found
+
+
+def _build(cls):
+ options = declarations.class_options(cls)
+ fields = cls._mcp_fields()
+ base = _base_names(cls)
+ properties, hidden_references = {}, {}
+
+ # Fields (a model's), as the class's _mcp_fields hook exposes them
+ for name, f in fields.items():
+ opts = f.options
+ if not isinstance(opts, dict):
+ if opts is None and f.holds_objects:
+ hidden_references[name] = object_classes(f.type_def)
+ continue
+ schema, description = property_schema(
+ f.type_def, opts, ref=reference_schema, can_be_null=f.nullable
+ )
+ properties[name] = Property(
+ name=name,
+ origin="field",
+ schema=schema,
+ description=description,
+ writable=not opts.get("read_only", False),
+ requires=opts.get("requires", ()),
+ reference=f.holds_objects,
+ type_def=f.type_def,
+ )
+
+ # Python properties: marked, or listed
+ for attr, member in _members(cls).items():
+ if attr in fields:
+ continue
+ if not isinstance(member, property):
+ continue
+ marker = getattr(member, PROPERTY_MARKER, None)
+ listed = options["properties"].get(attr)
+ if listed is False or (marker is None and listed is None):
+ continue
+ if attr in base:
+ msg = f"{cls.__name__}.{attr} is part of trame's API and cannot be exposed"
+ raise ValueError(msg)
+ opts = {**(marker or {}), **(listed or {})}
+ hint = return_hint(member.fget) if member.fget else None
+ schema, description = property_schema(hint, opts, ref=reference_schema)
+ properties[attr] = Property(
+ name=attr,
+ origin="property",
+ schema=schema,
+ description=description or docstring(member.fget),
+ writable=member.fset is not None and not opts.get("read_only"),
+ requires=opts.get("requires", ()),
+ set_requires=opts.get("set_requires", ()),
+ reference=bool(object_classes(hint)),
+ type_def=hint,
+ )
+
+ constructor, warning = _constructor(cls)
+ return TypeInfo(
+ cls=cls,
+ visible=True,
+ description=_description(cls, options),
+ properties=properties,
+ methods=_methods(cls, options, base),
+ constructor=constructor,
+ constructor_warning=warning,
+ hidden_references=hidden_references,
+ )
+
+
+def _description(cls, options):
+ """The class's own description option, else its own docstring; neither
+ is inherited."""
+ if options["description"]:
+ return options["description"]
+ doc = vars(cls).get("__doc__")
+ return unwrap(inspect.cleandoc(doc)) if doc else None
+
+
+def _methods(cls, options, base):
+ methods = {}
+ for attr, fn in _members(cls).items():
+ if not inspect.isfunction(fn):
+ continue # classmethods, staticmethods, properties, data
+ marker = fn.__dict__.get(METHOD_MARKER)
+ listed = options["methods"].get(attr)
+ if listed is False:
+ continue
+ automatic = (
+ options["all_methods"]
+ and not attr.startswith("_")
+ and attr not in base
+ and not any(m in fn.__dict__ for m in _CALLBACK_MARKERS)
+ )
+ if marker is None and listed is None and not automatic:
+ continue
+ if attr in base:
+ msg = f"{cls.__name__}.{attr} is part of trame's API and cannot be exposed"
+ raise ValueError(msg)
+ check_progress(fn, f"{cls.__name__}.{attr}")
+ opts = {**(marker or {}), **(listed or {})}
+ public = opts.get("name") or attr
+ if public in methods:
+ msg = f"{cls.__name__}: two methods are exposed as {public!r}"
+ raise ValueError(msg)
+ annotations = dict(opts.get("annotations") or {})
+ read_only = annotations.pop("readOnlyHint", False) or opts.get("read_only")
+ methods[public] = Method(
+ name=public,
+ attr=attr,
+ description=opts.get("description") or docstring(fn) or "",
+ read_only=bool(read_only),
+ annotations=annotations or None,
+ concurrent=bool(opts.get("concurrent", False)),
+ requires=tuple(opts.get("requires", ())),
+ )
+ return methods
+
+
+def _constructor(cls):
+ """``(Constructor or None, warning or None)``, from the class's
+ ``_mcp_constructor`` hook."""
+ declared = cls._mcp_constructor()
+ if declared is None:
+ return None, None
+ if declared.problem:
+ return None, declared.problem
+ if declared.attr is None:
+ constructor = Constructor(
+ attr=None,
+ description=declared.description,
+ requires=tuple(declared.requires),
+ )
+ return constructor, None
+
+ attr = declared.attr
+ member = inspect.getattr_static(cls, attr, None)
+ if not isinstance(member, classmethod):
+ msg = f"{cls.__name__}.{attr} is the constructor but is not a classmethod"
+ raise ValueError(msg)
+ parameters = list(inspect.signature(getattr(cls, attr)).parameters)
+ if not parameters:
+ msg = (
+ f"{cls.__name__}.{attr}: a constructor takes the trame server as its "
+ f"first parameter after cls"
+ )
+ raise ValueError(msg)
+ return (
+ Constructor(
+ attr=attr,
+ description=declared.description or docstring(member.__func__) or "",
+ requires=tuple(declared.requires),
+ server=parameters[0],
+ ),
+ None,
+ )
+
+
+def subclasses(cls):
+ """``cls`` and all its subclasses."""
+ result, stack = [], [cls]
+ while stack:
+ klass = stack.pop()
+ result.append(klass)
+ stack.extend(klass.__subclasses__())
+ return result
diff --git a/src/trame_server/protocol.py b/src/trame_server/protocol.py
index ac86569..dd5e08c 100644
--- a/src/trame_server/protocol.py
+++ b/src/trame_server/protocol.py
@@ -120,6 +120,7 @@ def set_server(self, _server):
self.server._server = _server
# Cookie on page responses: aiohttp only, other backends use the secret
auth_aiohttp.mount(_server, lambda: self.secret, lambda: self.server.port)
+ self.server._bind_mcp(_server)
if self.server.controller.on_server_bind.exists():
# wslink registers its static routes on start, so routes added
# here take precedence over them
@@ -141,6 +142,9 @@ def port_callback(self, port_used):
if self.server.controller.on_server_ready.exists():
self.server.controller.on_server_ready(**self.server.state.to_dict())
+ # Announce agent access (after the connection info printed above)
+ self.server._mcp_ready()
+
# Mark the server as ready
if not self.server.ready.done():
self.server.ready.set_result(True)
diff --git a/src/trame_server/state.py b/src/trame_server/state.py
index ea98f71..418211f 100644
--- a/src/trame_server/state.py
+++ b/src/trame_server/state.py
@@ -181,12 +181,16 @@ def __init__(
hot_reload=False,
ready=False,
exception_handler=None,
+ get_mcp=None,
):
self._push_state_fn = commit_fn
# Child states always report to the root state handler
self._exception_handler = share(
internal, "_exception_handler", exception_handler
)
+ # Returns the server's MCP; None for a state agents never see
+ # (server.context)
+ self._get_mcp = get_mcp
self._hot_reload = hot_reload
self._translator = translator or Translator()
self._modified_keys = share(internal, "_modified_keys", set())
@@ -548,6 +552,46 @@ def register_change_callback(func):
return register_change_callback
+ # -------------------------------------------------------------------------
+ # Agents (MCP)
+ # -------------------------------------------------------------------------
+
+ def _mcp(self):
+ if self._get_mcp is None:
+ msg = (
+ "This state cannot be exposed to agents (server.context is "
+ "server-only); expose keys of server.state instead"
+ )
+ raise RuntimeError(msg)
+ return self._get_mcp()
+
+ def mcp_expose(
+ self, name, *, type=None, schema=None, description=None, read_only=False
+ ):
+ """
+ Expose a state key to agents, as a property of the ``state`` object.
+ Writes are checked against ``type`` and ``schema`` and applied inside
+ ``with state:``, so ``@state.change`` reactions run and browsers update.
+ On a child server the key is translated: agents see the real key.
+
+ :param name: the state key
+ :param type: Python type of its values, e.g. ``int`` or ``list[float]``
+ :param schema: extra JSON Schema keywords (``minimum``, ``enum``, ...)
+ :param description: what agents read about it
+ :param read_only: agents may read it but not write it
+ """
+ self._mcp()._expose_state(
+ self._translator.translate_key(name),
+ type=type,
+ schema=schema,
+ description=description,
+ read_only=read_only,
+ )
+
+ def mcp_unexpose(self, *names):
+ """Withdraw state keys from agents."""
+ self._mcp()._unexpose_state(*self._translator.translate_list(names))
+
@contextmanager
def suppress_change_listeners(self, *keys: str):
"""
diff --git a/src/trame_server/utils/browser.py b/src/trame_server/utils/browser.py
index 2a3381a..377b080 100644
--- a/src/trame_server/utils/browser.py
+++ b/src/trame_server/utils/browser.py
@@ -1,9 +1,11 @@
from urllib.parse import urlencode
+from .server import http_scheme
+
def open_browser(server):
args = server.cli.parse_known_args()[0]
- local_url = f"http://{args.host}:{server.port}/"
+ local_url = f"{http_scheme(args)}://{args.host}:{server.port}/"
query = server.url_query_params
if query:
local_url = f"{local_url}?{urlencode(query)}"
diff --git a/src/trame_server/utils/server.py b/src/trame_server/utils/server.py
index 25a5191..681d031 100644
--- a/src/trame_server/utils/server.py
+++ b/src/trame_server/utils/server.py
@@ -2,11 +2,17 @@
import sys
from urllib.parse import urlencode
-from trame_server.auth import SECRET_PARAM
+from trame_server.auth import SECRET_PARAM, is_default
SECRET_PLACEHOLDER = ""
+def http_scheme(options):
+ """The scheme of the web server's URLs: ``https`` when it serves TLS
+ (``--ssl``), else ``http``."""
+ return "https" if getattr(options, "ssl", None) else "http"
+
+
def _secret_query(server):
"""The query string of the printed URLs, and a note to print after them.
@@ -24,7 +30,8 @@ def _secret_query(server):
def print_informations(server):
options = server.server_options
query, note = _secret_query(server)
- local_url = f"http://{options.host}:{server.port}/{query}"
+ scheme = http_scheme(options)
+ local_url = f"{scheme}://{options.host}:{server.port}/{query}"
print()
print("App running at:")
print(f" - Local: {local_url}")
@@ -35,9 +42,9 @@ def print_informations(server):
except Exception:
host_name = socket.gethostname()
host_ip = socket.gethostbyname(host_name)
- print(f" - Network: http://{host_ip}:{server.port}/{query}")
+ print(f" - Network: {scheme}://{host_ip}:{server.port}/{query}")
except socket.gaierror:
- print(f" - Network: http://{options.host}:{server.port}/{query}")
+ print(f" - Network: {scheme}://{options.host}:{server.port}/{query}")
if note:
print()
@@ -49,3 +56,38 @@ def print_informations(server):
flush=True,
)
sys.stdout.flush()
+
+
+def print_mcp_informations(mcp):
+ """Print how agents connect to ``mcp`` (a server's MCP): its URL, and the
+ commands that start a Claude Code or Codex session with this server added.
+ With wslink's default key, also a hint: the WebSocket lets anyone drive the
+ app, whatever the MCP checks. It takes the MCP rather than the server, since
+ it may run while ``server.mcp`` is being created."""
+ from trame_server.mcp import claude_command, codex_command # noqa: PLC0415
+
+ http = mcp.http
+ url, name = http.url, mcp.name
+ # As the WebSocket secret: shown, unless --mcp-hide-secret
+ hidden = mcp._shared.launch_options.hide_secret
+ secret = SECRET_PLACEHOLDER if hidden else http.secret
+ print()
+ print(f"MCP server available at {url}")
+ print(f" {claude_command(name, url, secret)}")
+ print(f" {codex_command(name, url, secret)}")
+ if hidden:
+ print(" The MCP key is not shown (--mcp-hide-secret).")
+ elif http._secret_generated:
+ print(
+ " (key generated for this run: set a fixed one with --mcp-auth-key,\n"
+ " --mcp-auth-key-file or TRAME_MCP_AUTH_KEY)"
+ )
+ protocol = mcp.server.protocol
+ if protocol is not None and is_default(protocol.secret):
+ print(
+ " Note: the app's WebSocket accepts wslink's public default key, so any\n"
+ " web page open in your browser, or anyone who can reach this port, can\n"
+ " drive the app through it. Launch with --authKey auto (or --authKeyFile)\n"
+ " to require a secret."
+ )
+ print(flush=True)
diff --git a/tests/test_mcp_call_log.py b/tests/test_mcp_call_log.py
new file mode 100644
index 0000000..19f8146
--- /dev/null
+++ b/tests/test_mcp_call_log.py
@@ -0,0 +1,304 @@
+"""The call log (``--mcp-log``): what agents call, logged once whichever way
+the call came in, through the standard ``logging`` module."""
+
+import asyncio
+import itertools
+import logging
+import re
+
+import pytest
+from trame.app import get_server
+
+from trame_server.mcp import Image
+from trame_server.mcp.call_log import shorten
+
+SESSION = "abcdef0123456789"
+LAUNCH_VARIABLES = (
+ "TRAME_ARGS",
+ "TRAME_MCP_AUTH_KEY",
+ "TRAME_MCP_AUTH_KEY_FILE",
+ "TRAME_MCP_LOG",
+ "TRAME_MCP_DENY",
+)
+MCP_LOGGER = logging.getLogger("trame_server.mcp")
+
+_counter = itertools.count()
+
+
+def rpc(method, params=None, rpc_id=1):
+ msg = {"jsonrpc": "2.0", "id": rpc_id, "method": method}
+ if params is not None:
+ msg["params"] = params
+ return msg
+
+
+class _Lines(logging.Handler):
+ def __init__(self):
+ super().__init__()
+ self.lines = []
+
+ def emit(self, record):
+ self.lines.append(record.getMessage())
+
+
+@pytest.fixture(autouse=True)
+def _no_launch_options(monkeypatch):
+ for name in LAUNCH_VARIABLES:
+ monkeypatch.delenv(name, raising=False)
+ # Launched with agent access on, which the tests may switch once running
+ monkeypatch.setenv("TRAME_ARGS", "--mcp --mcp-mutable activate")
+
+
+@pytest.fixture
+def pristine_logger():
+ """The MCP loggers as an application that never configured logging has
+ them (WARNING, Python's default; pytest lowers the root logger's),
+ restored afterwards (they are process-wide)."""
+ saved = MCP_LOGGER.handlers[:], MCP_LOGGER.level
+ MCP_LOGGER.handlers.clear()
+ MCP_LOGGER.setLevel(logging.WARNING)
+ yield MCP_LOGGER
+ MCP_LOGGER.handlers[:], MCP_LOGGER.level = saved
+
+
+@pytest.fixture
+def lines(pristine_logger):
+ """Every line the MCP loggers write, through a handler of the
+ application's own."""
+ handler = _Lines()
+ pristine_logger.addHandler(handler)
+ return handler.lines
+
+
+@pytest.fixture
+def logging_on(pristine_logger):
+ """What --mcp-log does: the MCP loggers at INFO."""
+ pristine_logger.setLevel(logging.INFO)
+
+
+def new_server():
+ return get_server(f"test_mcp_call_log_{next(_counter)}")
+
+
+@pytest.fixture
+def mcp(pristine_logger): # noqa: ARG001 - whatever a test turns on is undone
+ mcp = new_server().mcp
+ mcp.enabled = True
+ return mcp
+
+
+@pytest.fixture
+def tools(mcp):
+ @mcp.tool
+ def add(a: int, b: int = 1) -> int:
+ return a + b
+
+ @mcp.tool
+ def failing():
+ msg = "boom"
+ raise RuntimeError(msg)
+
+ @mcp.tool
+ def echo(text: str) -> str:
+ return text
+
+ @mcp.tool
+ def snapshot() -> list:
+ return [Image(b"\x89PNG" * 10), "a view"]
+
+ @mcp.resource("trame://info", mime_type="application/json")
+ def info():
+ return {"name": "test"}
+
+ @mcp.prompt
+ def walkthrough(topic: str = "app") -> str:
+ return f"Explain the {topic}"
+
+ return mcp
+
+
+@pytest.mark.asyncio
+async def test_off_by_default(tools, lines):
+ await tools.protocol.handle(
+ rpc("tools/call", {"name": "add", "arguments": {"a": 2}})
+ )
+ assert lines == []
+
+
+@pytest.mark.asyncio
+async def test_a_call_is_logged_once_when_it_ends(tools, lines, logging_on): # noqa: ARG001
+ response = await tools.protocol.handle(
+ rpc("tools/call", {"name": "add", "arguments": {"a": 2}}), session=SESSION
+ )
+ assert response["result"]["content"][0]["text"] == "3"
+ (line,) = lines
+ assert re.fullmatch(r"mcp\[abcdef\] add \{a: 2\} -> ok \d+\.\d\ds", line), line
+
+
+@pytest.mark.asyncio
+async def test_resources_and_prompts_too(tools, lines, logging_on): # noqa: ARG001
+ await tools.protocol.handle(rpc("resources/read", {"uri": "trame://info"}))
+ await tools.protocol.handle(rpc("prompts/get", {"name": "walkthrough"}))
+ resource, prompt = lines
+ assert re.fullmatch(r"mcp\[-\] resource trame://info -> ok \d+\.\d\ds", resource)
+ assert re.fullmatch(r"mcp\[-\] prompt walkthrough -> ok \d+\.\d\ds", prompt)
+
+
+@pytest.mark.asyncio
+async def test_in_process_calls_are_logged_too(tools, lines, logging_on): # noqa: ARG001
+ client = tools.client()
+ await client.call_tool("add", {"a": 1})
+ await client.read_resource("trame://info")
+ assert lines[0].startswith("mcp[in-process] add {a: 1} -> ok")
+ assert lines[1].startswith("mcp[in-process] resource trame://info -> ok")
+
+
+@pytest.mark.asyncio
+async def test_clients_without_a_session_are_named_by_themselves(
+ tools,
+ lines,
+ logging_on, # noqa: ARG001
+):
+ """In-process clients and clients of MCP 2026-07-28 have no session id:
+ the name they give (clientInfo) says who called, kept to safe
+ characters."""
+ await tools.client().call_tool("add", {"a": 1})
+ await tools.client("assistant").call_tool("add", {"a": 1})
+ await tools.client("my agent\n[x]").call_tool("add", {"a": 1})
+ meta = {
+ "io.modelcontextprotocol/protocolVersion": "2026-07-28",
+ "io.modelcontextprotocol/clientCapabilities": {},
+ "io.modelcontextprotocol/clientInfo": {"name": "claude-code", "version": "2"},
+ }
+ await tools.protocol.handle(
+ rpc("tools/call", {"name": "add", "arguments": {"a": 1}, "_meta": meta})
+ )
+ callers = [line.split("]")[0] + "]" for line in lines]
+ assert callers == [
+ "mcp[in-process]",
+ "mcp[assistant]",
+ "mcp[my_agent__x_]", # no newline or bracket of the name's own
+ "mcp[claude-code]",
+ ]
+
+
+@pytest.mark.asyncio
+async def test_failures_say_what_the_agent_saw(tools, lines, logging_on): # noqa: ARG001
+ await tools.protocol.handle(rpc("tools/call", {"name": "failing"}))
+ await tools.protocol.handle(
+ rpc("tools/call", {"name": "add", "arguments": {"a": "x"}})
+ )
+ await tools.protocol.handle(
+ rpc("tools/call", {"name": "missing", "arguments": {"q": 1}})
+ )
+ await tools.protocol.handle(rpc("resources/read", {"uri": "trame://nope"}))
+ # One line each: the failure is not logged a second time
+ failing, invalid, unknown, resource = (
+ line for line in lines if not line.startswith("Tool failing raised")
+ )
+ assert re.match(
+ r"mcp\[-\] failing -> error \d+\.\d\ds: RuntimeError: boom$", failing
+ )
+ assert 'add {a: "x"} -> error' in invalid
+ assert invalid.endswith(
+ "Invalid arguments for tool add: arguments.a: expected integer, got string"
+ )
+ assert unknown.startswith("mcp[-] missing {q: 1} -> error")
+ assert unknown.endswith("Unknown tool: missing")
+ assert resource.startswith("mcp[-] resource trame://nope -> error")
+ assert resource.endswith("Unknown resource: trame://nope")
+
+
+@pytest.mark.asyncio
+async def test_a_refused_permission_is_logged_as_denied(tools, lines, logging_on): # noqa: ARG001
+ tools.permissions.declare("files", "Read files", allowed=False)
+
+ @tools.tool(requires="files")
+ def read(path: str) -> str:
+ return path
+
+ await tools.protocol.handle(
+ rpc("tools/call", {"name": "read", "arguments": {"path": "/"}})
+ )
+ (line,) = lines
+ assert re.match(
+ r'mcp\[-\] read \{path: "/"\} -> denied \d+\.\d\ds: read: permission "files" '
+ r"\(Read files\) is off",
+ line,
+ ), line
+
+
+@pytest.mark.asyncio
+async def test_disabled_access_is_logged(tools, lines, logging_on): # noqa: ARG001
+ tools._start() # running, so that --mcp-mutable activate lets it switch
+ tools.enabled = False
+ await tools.protocol.handle(
+ rpc("tools/call", {"name": "add", "arguments": {"a": 1}})
+ )
+ (line,) = lines
+ assert "-> error" in line
+ assert line.endswith("MCP access is currently disabled by the application")
+
+
+@pytest.mark.asyncio
+async def test_a_cancelled_call(mcp, lines, logging_on): # noqa: ARG001
+ started = asyncio.Event()
+
+ @mcp.tool
+ async def wait_forever():
+ started.set()
+ await asyncio.Event().wait()
+
+ handling = asyncio.ensure_future(
+ mcp.protocol.handle(rpc("tools/call", {"name": "wait_forever"}, rpc_id=7))
+ )
+ await started.wait()
+ await mcp.protocol.handle(
+ {
+ "jsonrpc": "2.0",
+ "method": "notifications/cancelled",
+ "params": {"requestId": 7},
+ }
+ )
+ await handling
+ calls = [line for line in lines if line.startswith("mcp[")]
+ (line,) = calls
+ assert re.fullmatch(r"mcp\[-\] wait_forever -> cancelled \d+\.\d\ds", line), line
+
+
+@pytest.mark.asyncio
+async def test_long_arguments_are_shortened(tools, lines, logging_on): # noqa: ARG001
+ await tools.protocol.handle(
+ rpc("tools/call", {"name": "echo", "arguments": {"text": "x" * 500}})
+ )
+ assert lines[0].startswith("mcp[-] echo {text: } -> ok")
+
+
+def test_shorten():
+ assert (
+ shorten({"a": 1, "b": [True, None], "c": "hi"})
+ == '{a: 1, b: [true, null], c: "hi"}'
+ )
+ assert shorten(list(range(10))) == "[0, 1, 2, 3, 4, 5, 6, 7, +2]"
+ assert shorten({str(i): i for i in range(9)}).endswith(", 7: 7, +1}")
+ assert shorten({"a": {"b": {"c": {"d": 1}}}}) == "{a: {b: {c: {...}}}}"
+ assert shorten([[[[1]]]]) == "[[[[...]]]]"
+ assert shorten(object()) == "