Serve a toolkit, resources and prompts over the Model Context Protocol, and call another server's tools.
The Model Context Protocol lets an AI application use
tools, resources and prompts that another program serves. pyfect.ai.mcp_server serves
them from the same toolkits a LanguageModel uses, and
pyfect.ai.mcp_client connects to any MCP server. The server speaks the protocol's
revisions from 2024-11-05 to the stateless 2026-07-28; the client, as Effect's, speaks
2025-11-25 and 2026-07-28 only.
Serve a toolkit#
mcp_server.toolkit(Calculator) registers a toolkit's tools, with its handlers' layer
provided. Each tool is listed with its description, its parameters' JSON Schema and an
output schema; tool.Readonly, Destructive, Idempotent and OpenWorld annotations
become its hints. Invalid arguments and declared failures come back as tool errors the
model can read, and any other failure as an internal error that leaks no details. The
2025 revisions allow only an object as a structured result, so on them, as in Effect, a
tool whose result is another kind of value, such as a list, sends it as text content only,
with no structuredContent and no output schema in its listing.
A tool decodes its arguments with its parameters schema as it is, but lists that schema's
JSON form, as Effect does, so a parameter such as S.HashSet is listed as a JSON array yet
refuses one unless the tool's parameters= is wrapped in S.to_codec_json(...).
mcp_server.resource, resource_template and prompt add resources and prompts the same
way, as layers. Each of these layers needs the McpServer, so it can't be merged next to a
transport: pass it, or several merged, as the transport's registrations=, which builds them
against the transport's server before serving.
A transport layer serves them. mcp_server.layer_http(name=..., version=..., path=..., protocols=..., registrations=...) adds MCP's Streamable HTTP transport to an
HTTP router, with sessions and JSON or Server-Sent Event replies.
mcp_server.run_stdio(...) serves on standard input and output until the input ends, for
a server that a client starts as a child process; see
examples/mcp_server.py.
It returns when the input ends, so run_main exits 0. mcp_server.layer_stdio(...) is
Effect's form: the end of input interrupts the fiber that built the layer, so .launch()
under run_main exits 130, as Effect's does. Put the layer below your other layers with
layer.provide_merge. Under layer.merge it builds on a fiber of its own, which has finished
by then, so the program keeps running after the input ends, in Effect as well.
Connect a client#
mcp_client.layer_http(name=..., version=..., url=..., protocol=...) connects to a server
over HTTP, and layer_stdio(command=process.make(...), ...) starts one as a child process.
The McpClient then has the server's server_info and instructions, list_tools,
list_prompts and list_resources, call_tool(tool, arguments, schema=...) decoding the
result's structured content, get_prompt and read_resource. Failures are an
McpClientError whose reason says which: a tool error, a timeout (60 seconds by
default), a transport or protocol error. A tool error is a failure only with schema=:
without one, call_tool succeeds with the whole CallToolResult, so check its isError,
as with Effect's callTool.
from typing import TypedDict
import pyfect as fx
from pyfect import layer
from pyfect import schema as S
from pyfect.ai import mcp_client, mcp_protocol, mcp_server, tool, toolkit
from pyfect.http import live_server, router
class AddParams(TypedDict):
a: int
b: int
class Sum(TypedDict):
total: int
Add = tool.make(
"add", description="Add two integers", parameters=S.Struct(AddParams), success=S.Struct(Sum)
).annotate(tool.Readonly, True)
Calculator = toolkit.make(Add)
Handlers = Calculator.to_layer(
Add.handler(lambda params, _: fx.succeed(Sum(total=params["a"] + params["b"])))
)
# The server: the toolkit, served over MCP's Streamable HTTP transport at /mcp.
Server = mcp_server.layer_http(
name="calculator",
version="1.0.0",
path="/mcp",
protocols=(mcp_protocol.v2025_11_25, mcp_protocol.v2026_07_28),
registrations=mcp_server.toolkit(Calculator).pipe(layer.provide(Handlers)),
)
Served = router.serve(Server, disable_logger=True, disable_listen_log=True)
# The client: connects, lists the server's tools and calls one.
@fx.fn
def program():
client = yield from mcp_client.McpClient()
print("server", client.server_info)
tools = yield from client.list_tools()
print("tools", [(t["name"], t.get("description")) for t in tools])
total = yield from client.call_tool(tools[0], {"a": 2, "b": 3}, schema=S.Struct(Sum))
print("add", total)
Client = mcp_client.layer_http(
name="docs", version="1.0.0", url="/mcp", protocol=mcp_protocol.v2025_11_25
)
# layer_test: a server on a free local port, and an HttpClient sending to it.
fx.run_main(
program()
.pipe(fx.provide(Client))
.pipe(fx.provide(Served))
.pipe(fx.provide(live_server.layer_test()))
)mcp_client.toolkit(client, prefix) gives the server's tools as a toolkit with their
handlers, so generate_text(prompt, toolkit=...) lets a model call another program's
tools. Each model tool is named prefix followed by the server's name for it, joined as
they are, as in Effect: "docs__" gives docs__search, and "docs" gives docssearch.
Pass tools= a list you approved earlier (from list_tools) to bind exactly those
tools without listing them again, and timeout= to bound each call. The client's
capabilities say what the server offers.
A call's result is the tool result's text. With result_mode="complete" it is the whole
CallToolResult, and the model gets its content as text and file parts, so an image a
tool returns reaches the model as an image. A tool error from the server (isError)
fails the call with McpClientError by default. Pass failure_mode="return" to give it
to the model as a failed result instead, as a local tool with failure_mode="return"
does: the model gets the encoded McpClientError, the tool's own result for a tool
error, so it can read "no country has the code 'XX'" and answer. A request that fails,
such as a timeout or a closed transport, goes back to the model the same way.
The server describes its tools, so its hints are not trusted by default.
trust_annotations=True copies them (read-only, destructive, idempotent, open-world and
the title) into the tools' annotations. transform_tool gets each tool with its
descriptor and returns one derived from it, to ask for approval or add annotations; the
descriptor stays on the tool as mcp_client.ToolDescriptor.
from typing import Never, TypedDict, cast
import pyfect as fx
from pyfect import layer
from pyfect import schema as S
from pyfect.ai import mcp_client, mcp_protocol, mcp_schema, mcp_server, tool, toolkit
from pyfect.http import live_server, router
class AddParams(TypedDict):
a: int
b: int
class Sum(TypedDict):
total: int
Add = tool.make("add", parameters=S.Struct(AddParams), success=S.Struct(Sum))
Erase = tool.make("erase", success=S.String)
Tools = toolkit.make(Add.annotate(tool.Readonly, True), Erase)
Handlers = Tools.to_layer(
Add.handler(lambda params, _: fx.succeed(Sum(total=params["a"] + params["b"]))),
Erase.handler(lambda _, __: fx.succeed("erased")),
)
Server = mcp_server.layer_http(
name="calculator",
version="1.0.0",
path="/mcp",
protocols=(mcp_protocol.v2026_07_28,),
registrations=mcp_server.toolkit(Tools).pipe(layer.provide(Handlers)),
)
Served = router.serve(Server, disable_logger=True, disable_listen_log=True)
# Ask for approval of every tool that the server does not call read-only.
def approve_writes(
remote: mcp_client.RemoteTool[mcp_schema.CallToolResult, Never],
descriptor: mcp_schema.Tool,
) -> mcp_client.RemoteTool[mcp_schema.CallToolResult, Never]:
hints = descriptor.get("annotations", {})
return remote.set_needs_approval(hints.get("readOnlyHint") is not True)
@fx.fn
def program():
client = yield from mcp_client.McpClient()
print("capabilities", client.capabilities)
approved = yield from client.list_tools()
kit = yield from mcp_client.toolkit(
client,
"calc__",
tools=approved,
result_mode="complete",
failure_mode="return",
timeout="10 seconds",
transform_tool=approve_writes,
)
approval = {name: t.needs_approval for name, t in kit.tools.items()}
assert approval == {"calc__add": False, "calc__erase": True}
print("approval", approval)
results = yield from kit.handle("calc__add", {"a": 2, "b": 3})
[output] = yield from results.run_collect()
# The complete result, as the server sent it (with its 2026-07-28 ``_meta``).
result = cast("mcp_schema.CallToolResult", output.result)
assert result.get("isError") is False
assert result["content"] == [{"type": "text", "text": '{"total":5}'}]
assert result.get("structuredContent") == {"total": 5}
print("model sees", output.model_output)
Client = mcp_client.layer_http(
name="docs", version="1.0.0", url="/mcp", protocol=mcp_protocol.v2026_07_28
)
fx.run_main(
program()
.pipe(fx.provide(Client))
.pipe(fx.provide(Served))
.pipe(fx.provide(live_server.layer_test()))
)Each request is a span on both sides, named for its method: McpClient.tools/call on
the client and McpServer.tools/call on the server, each with a tool attribute, inside
the trace of the HTTP request that carries it.
Return failures as plain text#
With failure_mode="return" the model gets the encoded McpClientError, so a tool's
text sits as JSON inside its reason, and some models answer that with an empty reply.
The model sees a failure as the tool's failure schema encodes it, so give the tool a
schema that encodes the McpClientError as its message. For a tool error that is the
tool's own text after Effect's prefix, MCP tool reported an error: <text>, as the output
below shows. transform_tool sets it with set_failure: the schema's type is still
McpClientError, so the application gets the same error, and only what the model reads
changes. The schema can't decode, because text doesn't carry the whole error.
from typing import Never, TypedDict
import pyfect as fx
from pyfect import layer
from pyfect import schema as S
from pyfect.ai import mcp_client, mcp_protocol, mcp_schema, mcp_server, tool, toolkit
from pyfect.ai.mcp_client_error import MCP_CLIENT_ERROR, McpClientError
from pyfect.http import live_server, router
from pyfect.schema import getter as G
from pyfect.schema import transformation as T
class CountryParams(TypedDict):
code: str
Country = tool.make(
"country",
parameters=S.Struct(CountryParams),
success=S.String,
failure=S.String,
failure_mode="return",
)
Tools = toolkit.make(Country)
Handlers = Tools.to_layer(
Country.handler(lambda params, _: fx.fail(f"no country has the code {params['code']!r}"))
)
Server = mcp_server.layer_http(
name="atlas",
version="1.0.0",
path="/mcp",
protocols=(mcp_protocol.v2026_07_28,),
registrations=mcp_server.toolkit(Tools).pipe(layer.provide(Handlers)),
)
Served = router.serve(Server, disable_logger=True, disable_listen_log=True)
# The model sees a failure as its encoding by the tool's failure schema. This one
# encodes an McpClientError as its message, which holds the tool's own text; the
# application still gets the McpClientError.
PlainText = S.String.pipe(
S.decode_to(
S.to_type(MCP_CLIENT_ERROR),
T.Transformation(
decode=G.forbidden(lambda _: "a plain-text failure cannot be decoded"),
encode=G.transform(lambda error: error.message),
),
)
)
def plain_failures(
remote: mcp_client.RemoteTool[str, Never], _: mcp_schema.Tool
) -> mcp_client.RemoteTool[str, Never]:
return remote.set_failure(PlainText)
@fx.fn
def program():
client = yield from mcp_client.McpClient()
kit = yield from mcp_client.toolkit(
client,
"atlas__",
failure_mode="return",
timeout="10 seconds",
transform_tool=plain_failures,
)
results = yield from kit.handle("atlas__country", {"code": "XX"})
[output] = yield from results.run_collect()
assert output.is_failure
assert isinstance(output.result, McpClientError)
print("model sees", repr(output.encoded_result))
Client = mcp_client.layer_http(
name="docs", version="1.0.0", url="/mcp", protocol=mcp_protocol.v2026_07_28
)
fx.run_main(
program()
.pipe(fx.provide(Client))
.pipe(fx.provide(Served))
.pipe(fx.provide(live_server.layer_test()))
)Strict tools#
A tool annotated tool.Strict lists a closed input schema (additionalProperties: false
on every object) and the server refuses arguments with unknown keys before the handler
runs, naming each one. Like Effect, it reports the refusal as an error result on
revisions that do so (2025-11-25 and later) and as an InvalidParams error before them.
from typing import TypedDict
import pyfect as fx
from pyfect import layer
from pyfect import schema as S
from pyfect.ai import mcp_client, mcp_protocol, mcp_server, tool, toolkit
from pyfect.http import live_server, router
class Greeting(TypedDict):
name: str
# A strict tool advertises a closed input schema and refuses unknown keys
# before its handler runs.
Greet = tool.make("greet", parameters=S.Struct(Greeting), success=S.String).annotate(
tool.Strict, True
)
Greeter = toolkit.make(Greet)
Handlers = Greeter.to_layer(Greet.handler(lambda params, _: fx.succeed(f"hi {params['name']}")))
Server = mcp_server.layer_http(
name="greeter",
version="1.0.0",
path="/mcp",
protocols=(mcp_protocol.v2025_11_25,),
registrations=mcp_server.toolkit(Greeter).pipe(layer.provide(Handlers)),
)
Served = router.serve(Server, disable_logger=True, disable_listen_log=True)
@fx.fn
def program():
client = yield from mcp_client.McpClient()
[greet] = yield from client.list_tools()
print("additionalProperties", greet["inputSchema"].get("additionalProperties"))
print((yield from client.call_tool(greet, {"name": "Ada"}))["content"])
# A misspelt key is refused; on 2025-11-25 the refusal is an error result.
typo = yield from client.call_tool(greet, {"name": "Ada", "nmae": "Ada"})
assert typo.get("isError") is True
[content] = typo["content"]
print(content.get("text"))
Client = mcp_client.layer_http(
name="docs", version="1.0.0", url="/mcp", protocol=mcp_protocol.v2025_11_25
)
fx.run_main(
program()
.pipe(fx.provide(Client))
.pipe(fx.provide(Served))
.pipe(fx.provide(live_server.layer_test()))
)Logging and protocol checks#
A client's logging/setLevel sets its session's threshold: log notifications below it are
dropped, and until it sets one the threshold is the CurrentLogLevel the server was built
with (Info unless you provide another), so debug messages are not sent by default. Handlers run with CurrentLogLevel at the session's level
(notice is Effect's Info, critical and above are Fatal). On 2026-07-28 each request
names its own level in _meta["io.modelcontextprotocol/logLevel"], and gets only the logs
at that level or above, and only the progress of its own progressToken.
The HTTP endpoint checks headers before it runs anything, as Effect does: a
MCP-Protocol-Version the server does not speak gets a 400 with error -32022 and the
supported versions, and a header that disagrees with the session or with a 2026-07-28
request's _meta, Mcp-Method or Mcp-Name gets -32020. A 2025-03-26 session may send
JSON-RPC batches (over HTTP and stdio); their answers come back as one array. Over HTTP, if
the batch's handlers send notifications, the reply is an event stream: the notifications, then
the array. A cancelled request in a batch gets no answer.
Subscriptions#
On 2026-07-28 a client asks for change notifications with one long subscriptions/listen
request. The answer is an event stream that opens with an acknowledgment naming the filters
the server honors (toolsListChanged, promptsListChanged, resourcesListChanged,
resourceSubscriptions), then carries only what matches, each with the request's id in
_meta["io.modelcontextprotocol/subscriptionId"]. Changes of one kind made in the same
scheduling window go out once. Idle HTTP streams get a comment every 15 seconds.
Each stream has a backlog of 64 notifications. A client that falls that far behind loses
its subscription and nobody else is held up: over HTTP the stream ends, over stdio it gets
notifications/cancelled with the request's id. Before 2026-07-28 clients get list changes
unasked and, over stdio, resources/subscribe. To turn subscriptions off, pass
allow_subscriptions=False to mcp_server.layer_http: discovery advertises no list changes
and subscriptions/listen is method not found. A custom transport turns them off itself (see
Custom transports).
import json
from typing import Any
import pyfect as fx
from pyfect.ai import mcp_protocol, mcp_server
from pyfect.http import HttpClient, live_server, router
from pyfect.http import request as R
METADATA: dict[str, Any] = {
"io.modelcontextprotocol/protocolVersion": "2026-07-28",
"io.modelcontextprotocol/clientCapabilities": {},
}
Server = mcp_server.layer_http(
name="watched",
version="1.0.0",
path="/mcp",
protocols=(mcp_protocol.v2026_07_28,),
)
Served = router.serve(Server, disable_logger=True, disable_listen_log=True)
def tool(name: str) -> mcp_server.ToolEntry:
return mcp_server.ToolEntry(
{"name": name, "inputSchema": {"type": "object"}},
fx.Context.empty(),
lambda _: fx.succeed({"content": []}),
)
listen = (
R.post("/mcp")
.body_text(
json.dumps(
{
"jsonrpc": "2.0",
"id": "tools-watch",
"method": "subscriptions/listen",
"params": {"notifications": {"toolsListChanged": True}, "_meta": METADATA},
}
),
"application/json",
)
.set_headers(
{
"accept": "application/json, text/event-stream",
"mcp-protocol-version": "2026-07-28",
"mcp-method": "subscriptions/listen",
}
)
)
# The stream's events, as they arrive: its acknowledgment, then the changes it asked for.
@fx.fn
def program():
server = yield from mcp_server.McpServer()
yield from server.add_tool(tool("first"))
client = yield from HttpClient()
response = yield from client.execute(listen)
pull = yield from response.stream.to_pull()
@fx.fn
def event():
chunks = yield from pull
text = b"".join(chunks).decode()
message = json.loads(text.removeprefix("data: "))
print(message["method"], message["params"].get("notifications", ""))
yield from event()
yield from server.add_tool(tool("second"))
yield from event()
fx.run_main(
program().pipe(fx.scoped).pipe(fx.provide(Served)).pipe(fx.provide(live_server.layer_test()))
)Adding a tool, prompt or resource sends its list change for you. When a resource's content
changes, say so with server.notify("notifications/resources/updated", {"uri": uri}) on the
McpServer: it reaches the subscriptions that named that URI in resourceSubscriptions
(and, before 2026-07-28, the stdio clients that sent resources/subscribe for it).
A route on the router layer_http serves can't ask for that McpServer per request:
provide_merge(layer_http(...)) doesn't remove the handler's Requires[McpServer], as in
Effect, where it stays a request requirement too. Take the server while the route's layer
builds instead, in router.use, as Effect's HttpRouter.use does, and the handler closes
over it:
import json
from typing import Any
import pyfect as fx
from pyfect.ai import mcp_protocol, mcp_server
from pyfect.http import HttpClient, live_server, router, server_response
from pyfect.http import request as R
URI = "note://today"
note = {"text": "draft"}
Note = mcp_server.resource(uri=URI, name="today", content=fx.sync(lambda: note["text"]))
Server = mcp_server.layer_http(
name="notes",
version="1.0.0",
path="/mcp",
protocols=(mcp_protocol.v2026_07_28,),
registrations=Note,
)
# The route takes the McpServer when the layer builds, not per request, so
# `provide_merge(Server)` below gives it the server built on the same router.
@fx.fn
def add_routes(routes: router.HttpRouterService):
server = yield from mcp_server.McpServer()
@fx.fn
def save():
note["text"] = "final"
yield from server.notify("notifications/resources/updated", {"uri": URI})
return (yield from server_response.json({"saved": True}))
yield from routes.add("POST", "/notes", save())
Routes = router.use(add_routes).pipe(fx.layer.provide_merge(Server))
Served = router.serve(Routes, disable_logger=True, disable_listen_log=True)
METADATA: dict[str, Any] = {
"io.modelcontextprotocol/protocolVersion": "2026-07-28",
"io.modelcontextprotocol/clientCapabilities": {},
}
listen = (
R.post("/mcp")
.body_text(
json.dumps(
{
"jsonrpc": "2.0",
"id": "note-watch",
"method": "subscriptions/listen",
"params": {"notifications": {"resourceSubscriptions": [URI]}, "_meta": METADATA},
}
),
"application/json",
)
.set_headers(
{
"accept": "application/json, text/event-stream",
"mcp-protocol-version": "2026-07-28",
"mcp-method": "subscriptions/listen",
}
)
)
@fx.fn
def program():
client = yield from HttpClient()
response = yield from client.execute(listen)
pull = yield from response.stream.to_pull()
@fx.fn
def event():
chunks = yield from pull
message = json.loads(b"".join(chunks).decode().removeprefix("data: "))
params = message["params"]
print(message["method"], params.get("uri", params.get("notifications")))
yield from event()
yield from client.execute(R.post("/notes"))
yield from event()
fx.run_main(
program().pipe(fx.scoped).pipe(fx.provide(Served)).pipe(fx.provide(live_server.layer_test()))
)Request-scoped servers#
mcp_server.layer_http_request_scoped serves 2026-07-28 with each POST's work belonging to
that request, for hosts that end everything with the response, such as serverless platforms.
When the client goes away the handler is interrupted, and handlers see the request's services
over the layer's. Tools, resources, prompts, completions and a request's own progress and logs
work as in layer_http. There are no subscriptions or broadcast notifications, DELETE gets
405, and a sessionful revision in protocols is a type error.
Sessions are not what lets a tool ask its client something on this revision. A tool or prompt
handler returns mcp_schema.InputRequired with keyed requests (roots/list,
sampling/createMessage, elicitation/create), an opaque request_state, or both. The client
retries with its answers, which the handler reads from McpRequestContext's input_responses
and request_state. Requests go out in 2026-07-28's form, so keys it does not carry (such as a
URL elicitation's elicitationId) are dropped and a malformed one is error -32603. A request whose capabilities the client did not declare gets a 400 with
error -32021 and the missing requiredCapabilities; on earlier revisions a tool's
InputRequired is invalid params. A 2026-07-28 HTTP request must also mirror each parameter
annotated x-mcp-header in its Mcp-Param-<name> header, plain or as =?base64?...?=, or it
gets a 400 with error -32020 before the tool runs.
import json
from typing import Any
import pyfect as fx
from pyfect import layer
from pyfect.ai import mcp_protocol, mcp_schema, mcp_server
from pyfect.http import HttpClient, live_server, router
from pyfect.http import request as R
METADATA: dict[str, Any] = {
"io.modelcontextprotocol/protocolVersion": "2026-07-28",
"io.modelcontextprotocol/clientCapabilities": {"elicitation": {"form": {}}},
}
APPROVAL: mcp_schema.ElicitationInputRequest = {
"method": "elicitation/create",
"params": {
"message": "Delete the file?",
"requestedSchema": {
"type": "object",
"properties": {"approved": {"type": "boolean"}},
"required": ["approved"],
},
},
}
# A tool that needs input returns InputRequired; the client retries with its answers.
def delete_file(
_: Any,
) -> fx.Effect[mcp_schema.CallToolResult | mcp_schema.InputRequired, Any, Any]:
def decide(
request: mcp_schema.RequestContext,
) -> mcp_schema.CallToolResult | mcp_schema.InputRequired:
answer = (request.input_responses or {}).get("approval")
if answer is None:
return mcp_schema.InputRequired(input_requests={"approval": APPROVAL})
return {"content": [{"type": "text", "text": f"approved: {answer['action']}"}]}
return mcp_schema.McpRequestContext().map(decide)
register = mcp_server.McpServer().flat_map(
lambda server: server.add_tool(
mcp_server.ToolEntry(
{"name": "delete_file", "inputSchema": {"type": "object"}},
fx.Context.empty(),
delete_file,
)
)
)
# Each POST's work belongs to that request: nothing runs on after its response.
Server = layer.effect_discard(register).pipe(
layer.provide_merge(
mcp_server.layer_http_request_scoped(
name="files",
version="1.0.0",
path="/mcp",
protocols=(mcp_protocol.v2026_07_28,),
)
)
)
Served = router.serve(Server, disable_logger=True, disable_listen_log=True)
def call(**continuation: Any) -> R.HttpClientRequest:
params: dict[str, Any] = {
"name": "delete_file",
"arguments": {},
"_meta": METADATA,
**continuation,
}
return (
R.post("/mcp")
.body_text(
json.dumps({"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": params}),
"application/json",
)
.set_headers(
{
"accept": "application/json, text/event-stream",
"mcp-protocol-version": "2026-07-28",
"mcp-method": "tools/call",
"mcp-name": "delete_file",
}
)
)
@fx.fn
def program():
client = yield from HttpClient()
first: Any = yield from (yield from client.execute(call())).json
print(first["result"]["resultType"], list(first["result"]["inputRequests"]))
answers = {"approval": {"action": "accept", "content": {"approved": True}}}
second: Any = yield from (yield from client.execute(call(inputResponses=answers))).json
print(second["result"]["resultType"], second["result"]["content"][0]["text"])
fx.run_main(program().pipe(fx.provide(Served)).pipe(fx.provide(live_server.layer_test())))McpClient can't answer InputRequired, as Effect's can't: it declares no capability that
lets a server ask it for input, so a tool that asks fails with an HttpError reason carrying code -32021, and
an input_required result that reaches it anyway fails with UnsupportedError. Call such
tools from a client that implements the continuation.
Custom transports#
mcp_server.layer_rpc_protocol (or the effect mcp_server.run) serves MCP over any RPC server
transport, the rpc.server.ServerProtocol you provide, as Effect's McpServer.layer does. Each
client of the transport is a session keyed by its client id. Requests arrive as RPC Request
messages (tag the method, payload the params) and answers leave as Exit messages;
notifications and requests to the client are Request messages too. A transport made with
supports_notifications=False can't write to a client unasked, so the server sends it no
notifications and serves no subscriptions: 2026-07-28 discovery advertises no list changes and
subscriptions/listen is method not found. A transport that reports client_ids has the
sessions of clients that left forgotten the next time a notification goes out.
from typing import Any
import pyfect as fx
from pyfect import layer
from pyfect.ai import mcp_protocol, mcp_server
from pyfect.rpc import serialization, server
METADATA: dict[str, Any] = {
"io.modelcontextprotocol/protocolVersion": "2026-07-28",
"io.modelcontextprotocol/clientCapabilities": {},
"io.modelcontextprotocol/clientInfo": {"name": "client", "version": "1.0.0"},
}
# A transport that queues what the server sends and cannot write to a client unasked.
@fx.fn
def queue_transport(sent: fx.Queue[Any], ready: fx.Deferred[server.WriteRequest]):
disconnects = fx.Queue[int]()
def parts(write: server.WriteRequest) -> fx.Effect[server.ProtocolParts]:
return ready.succeed(write).as_(
server.ProtocolParts(
disconnects=disconnects,
send=lambda _client, message: sent.offer(message).as_void(),
end=lambda _client: fx.void,
supports_ack=False,
supports_span_propagation=False,
codec_for=serialization.json.codec_for,
supports_notifications=False,
)
)
return (yield from server.with_run(parts))
def tool(name: str) -> mcp_server.ToolEntry:
return mcp_server.ToolEntry(
{"name": name, "inputSchema": {"type": "object"}},
fx.Context.empty(),
lambda _: fx.succeed({"content": []}),
)
@fx.fn
def program():
sent = fx.Queue[Any]()
ready = fx.Deferred[server.WriteRequest]()
transport = yield from queue_transport(sent, ready)
served = mcp_server.layer_rpc_protocol(
name="custom", version="1.0.0", protocols=(mcp_protocol.v2026_07_28,)
).pipe(layer.provide(layer.succeed(server.ServerProtocol, transport)))
context = yield from served.build()
yield from context.get(mcp_server.McpServer).add_tool(tool("search"))
write = yield from ready.wait()
listen = {"notifications": {"toolsListChanged": True}}
for id, method, params in [(1, "server/discover", {}), (2, "subscriptions/listen", listen)]:
payload = {"_meta": METADATA, **params}
yield from write(
0, {"_tag": "Request", "id": id, "tag": method, "payload": payload, "headers": []}
)
exit = (yield from sent.take())["exit"]
if exit["_tag"] == "Success":
print(method, exit["value"]["capabilities"]["tools"])
else:
print(method, exit["cause"][0]["error"]["message"])
fx.run_main(fx.scoped(program()))Skills#
The Skills extension (SEP-2640) serves Agent Skills: a SKILL.md
with YAML frontmatter and the files it refers to. mcp_server.skill(uri, files) registers
one at skill://<path>/SKILL.md, whose last path segment must be the frontmatter's name.
Each file becomes a resource, skills/list and skills/get list the skill with the SHA-256
digest and size of every file, and resources/directory/read browses the namespace. The
server declares io.modelcontextprotocol/skills once a skill is registered. Registration
fails with IllegalArgumentError when the frontmatter is not valid Agent Skills frontmatter,
a path leaves the skill, two skills overlap, or a file's URI is already a resource; a
resource registered later at a skill file's URI is a defect.
The client's skill methods need extensions={"skills": True}: list_skills, get_skill,
read_resource_directory and read_skill_resource. They call only a server that declares
the extension, and read_skill_resource fails with a ValidationError unless the bytes
match the listed digest and, for SKILL.md, the frontmatter matches the listing. An invalid
listed skill fails list_skills, unless on_invalid_skill is given: it is told of each one,
which is left out. Every list scan is bounded by discovery_limits (100 pages and 10,000
items by default), which limits= overrides per call.
import pyfect as fx
from pyfect import layer
from pyfect.ai import mcp_client, mcp_protocol, mcp_server
from pyfect.http import live_server, router
# A skill is a SKILL.md with YAML frontmatter plus the files it refers to.
Refunds = mcp_server.skill(
"skill://billing/refunds/SKILL.md",
{
"SKILL.md": "---\nname: refunds\ndescription: Process refunds\n---\n\n"
"Read references/policy.md before issuing a refund.\n",
"references/policy.md": "Refunds above CHF 500 need approval.\n",
},
)
Server = Refunds.pipe(
layer.provide_merge(
mcp_server.layer_http(
name="billing", version="1.0.0", path="/mcp", protocols=(mcp_protocol.v2026_07_28,)
)
)
)
Served = router.serve(Server, disable_logger=True, disable_listen_log=True)
@fx.fn
def program():
client = yield from mcp_client.McpClient()
[refunds] = yield from client.list_skills()
print(refunds["uri"], refunds["frontmatter"])
children = yield from client.read_resource_directory("skill://billing/refunds")
print([child["name"] for child in children])
# The bytes are checked against the SHA-256 digest the skill listed.
policy = yield from client.read_skill_resource(
refunds, "skill://billing/refunds/references/policy.md"
)
print(policy["contents"][0].get("text"))
Client = mcp_client.layer_http(
name="docs",
version="1.0.0",
url="/mcp",
protocol=mcp_protocol.v2026_07_28,
extensions={"skills": True},
)
fx.run_main(
program()
.pipe(fx.provide(Client))
.pipe(fx.provide(Served))
.pipe(fx.provide(live_server.layer_test()))
)Middleware and visibility#
mcp_server.middleware(fn, provides=...) runs fn(effect, options) around each
tools/call, resources/read, prompts/get and completion/complete of the registrations
its .layer is provided to. options carries the method, the target (a tool or prompt name,
a URI), the payload, the request context, the HTTP headers and the session id. It can provide
services to the handler (named in provides, so the layer discharges them from the
registrations' requirements), run before or after it, or fail with an McpError, which the
client gets as a JSON-RPC error with that code and message. Pick custom codes from -32000
to -32019, as Effect advises: any code is sent as is, but MCP uses -32020 to -32022 for its
own header, capability and protocol-version errors. .layer_global, or
global_=True, runs it around every request of the server, outside the local middleware;
middleware provided both ways runs once. a.combine(b) runs a inside b, and middleware
provided further out runs outside all of a combination.
The result is a Middleware[P, R, LE]: what it provides, what it needs (per request and to
be built) and what building it may fail with. A def middleware types its handler as
fx.Effect[mcp_server.MiddlewareSuccess, McpError, P] with P what it provides (Never for
none); typed Any, the middleware's types are Any too. combine discharges what b
provides only when that is all a needs, so combine inside out:
rate.combine(visible.combine(auth)).
mcp_server.visibility(check) is middleware that hides registrations per request: where
check gives False the registration is left out of tools/list, resources/list,
resources/templates/list and prompts/list, and a request for it fails as if it were not
registered. It sees what the middleware outside it provides, so combine it inside the
middleware it reads from. On a list only the middleware outside the innermost visibility
runs, once per registration, and its failure fails the list.
from typing import Any
import pyfect as fx
from pyfect import layer
from pyfect import schema as S
from pyfect.ai import mcp_protocol, mcp_server, mcp_test, tool, toolkit
from pyfect.context import Tag
class CurrentUser(Tag[str], key="app/CurrentUser"):
pass
# Middleware provides the user to the handlers inside it; the visibility reads it.
user = {"name": "guest"}
Auth = mcp_server.middleware(
lambda effect, _: effect.pipe(fx.provide_service(CurrentUser, user["name"])),
provides=CurrentUser,
)
AdminOnly = mcp_server.visibility(lambda _: CurrentUser().map(lambda name: name == "admin"))
WhoAmI = tool.make("who_am_i", success=S.String, dependencies=[CurrentUser])
Admin = toolkit.make(WhoAmI)
Handlers = Admin.to_layer(WhoAmI.handler(lambda _, __: CurrentUser()))
# The visibility runs inside Auth, so Auth's user is what it checks.
Registrations = (
mcp_server.toolkit(Admin)
.pipe(layer.provide(AdminOnly.combine(Auth).layer))
.pipe(layer.provide(Handlers))
)
@fx.fn
def program():
client = yield from mcp_test.make_client(Registrations, protocols=(mcp_protocol.v2025_11_25,))
for name in ("guest", "admin"):
user["name"] = name
tools = yield from client.list_tools()
called: Any = yield from client.call_tool({"name": "who_am_i"}).match(
on_failure=lambda error: error.message,
on_success=lambda result: result["content"][0],
)
print(name, [t["name"] for t in tools["tools"]], called)
fx.run_main(program().pipe(fx.scoped))mcp_test.make_client(registrations, protocols=...) is Effect's McpTest: it builds a server
with the registrations, connects an in-memory client and performs the handshake, so a test
calls tools through the server's routing, middleware and encoding as a wire client would.
Every message is written as JSON text and read back, both ways, as on stdio and HTTP, so a
result holds lists where the server's value had tuples, exactly as a wire client reads it. A
request answered with an error fails with an McpError of that code; the server's
notifications arrive on client.notifications, and its requests to the client get method not
found.
Cache hints#
On 2026-07-28, list and discovery results carry ttlMs and cacheScope: "private", with a
ttlMs of 0 unless the transport's cache_hints= says otherwise, such as
{"tools": {"ttl": "1 minute", "cache_scope": "private"}} for tools/list. The kinds are
discover, tools, resources, resource_templates, prompts and skills; ttl is sent
in whole milliseconds, rounded down. A hint that can't be sent (negative, infinite, past
2**53 - 1 milliseconds, unparsable, or not "private") fails the layer with
IllegalArgumentError. A hint lets a client keep a list after it changed, and a client
shared between users reuse one user's list for another, so give one only to lists that are
the same for everyone.
Security defaults#
mcp_server.layer_httpkeeps at mostmax_sessions(1000) sessions and answers 503 when they are all in use; a session idle forsession_idle_timeout(30 minutes) expires. A message larger thanmax_message_bytes(4 MiB, and never more than the app'sMaxBodySize) gets a 413, and so does aninitializelarger thanmax_initialize_bytes(64 KiB). A session keeps only the decodedinitializefields.- A defect in a tool, resource, prompt or completion handler, or in middleware, is logged and
reported, and the client gets "Internal error" (code -32603); a tool call gets a generic
tool error instead. A declared failure with a message sends only its message; one without a
message sends its fields through their JSON codec, as Effect 4.1.2 does, which writes a
Redactedfield's value: keep secrets out of a declared failure's fields. - Replies to the server's own requests (roots, sampling, elicitation) are decoded with their result schema; a malformed elicitation reply counts as declined.
- The client reads each server message under
max_message_bytes(16 MiB by default) and fails with aLimitErrorreason past it. JSON nested too deeply to parse is a parse error on both sides, not a crash.
Reference: mcp_server,
mcp_client,
mcp_protocol.