MCP registration, transport wrappers, and policy records
Explicit tool registration and scoped client sessions over the official MCP SDK. The root module imports `mcp` or `fastmcp` only inside server `create` and the stdio or HTTP session helpers; the host, client, server, and gateway modules do not import those SDKs.
The recohut_kit.mcp package is where the kit wires the official Model Context Protocol SDK into explicit, reviewable shapes. At the root it registers trusted native callables and builds compatible server and client wrappers for both MCP 1.x and 2.x. The root opens stdio sessions with a caller environment and timeout, and Streamable HTTP sessions with caller headers and a timeout. Around that core, sibling modules hold dependency-free design records for servers and hosts, client-side resolution and capability policies, shared protocol datatypes, and capability paging and validation helpers. Gateway pinning fingerprints published tool metadata and diffs two discoveries; shaping projects a handler row before the model sees it.
Nothing here runs an agent loop, chooses tools for a model, or performs implicit authentication on HTTP. Registry metadata does not grant execution trust. Subprocess stdio sessions are not a sandbox. The root module does not import mcp or fastmcp at import time; the SDK loads only when you create a server, open a session, or call into code that explicitly imports it.
Purpose
MCP is a protocol for hosts and tools to communicate. It does not itself decide which tool should be used or whether a proposed operation is authorized.
What this package owns. Deterministic registration and transport glue over the installed mcp package (and fastmcp for FastMCPServer), including version-line differences in server class names, HTTP host/port placement, result attribute naming, and Streamable HTTP client symbol names. It owns frozen policy and contract datatypes for MCP servers (tools, prompts, resources, lifecycle, evaluation), hosts (transports, capabilities, content adaptation, retries, resource selection), clients (registry resolution, namespaces, OAuth records, sampling and roots policies, assembly receipts), capabilities (completion windows, logging, cursors, elicitation validation), and the gateway’s tool fingerprinting plus response projection with redaction receipts.
What it deliberately does not own. Annotation-derived tool schemas stay with the SDK server, and hosts.content.to_native_tool also checks the input schema with Draft202012Validator. Holding an approved tool fingerprint and deciding whether a changed tool may run is host responsibility (gateway.pinning only compares fingerprints). Grounding a model reply, provider SDK imports in host turn contracts, and distributed rate limiting live in other kit layers. The gateway package docstring says the importer, the registry, and the front door remain unbuilt and outside this package.
Public API
Root (recohut_kit.mcp)
| Name | Kind | What it does |
|---|---|---|
ToolRegistration | dataclass | Trusted native callable; SDK annotations define its input schema |
ToolServer | protocol | register tools and unwrap the native server |
ToolClient | protocol | call a tool by name and unwrap the native session |
Transport | type alias | "stdio" or "streamable-http" |
MCPServer | class | Wraps the official SDK server; create, run, register, register_plugins, unwrap |
FastMCPServer | class | Subclasses MCPServer, registers through FastMCP tool(), and create always builds fastmcp.FastMCP while holding host and port for run |
MCPClient | class | Wraps a native session; call returns the native CallToolResult unchanged |
result_wire | function | JSON wire view of a native result with camelCase keys on both SDK lines |
result_is_error | function | Reads isError from that wire view for 1.x and 2.x |
http_session | async context manager | Opens Streamable HTTP; caller supplies headers; no implicit auth |
stdio_session | async context manager | Spawns stdio child with process_environment; caller authorizes command and env |
call_tool_sync | function | One-shot sync tool call; refuses inside a running event loop |
Protocol (recohut_kit.mcp.protocol)
| Name | Kind | What it does |
|---|---|---|
IconRecord | dataclass | Application-selected icon metadata; icon source grants no filesystem access |
ServerInfo | dataclass | Server identity fields observed from initialize; excludes arbitrary settings |
PromptArgument | dataclass | One prompt argument; required defaults false per MCP schema |
Gateway (recohut_kit.mcp.gateway)
| Name | Kind | What it does |
|---|---|---|
tool_fingerprint | function | Stable SHA-256 over name, description, input schema, and behaviour hints |
PinDiff | dataclass | Added, changed, and removed tool names between pin sets |
diff_pins | function | Compares pinned fingerprints to a fresh discovery keyed by tool name |
Projection | dataclass | Ordered declared fields for a tool response shape |
ProjectionRefused | exception | Raised when requested names a field the tool did not declare |
ShapingReceipt | dataclass | Byte sizes, returned, dropped, and missing field names, and a redaction count; not the dropped or redacted values |
shape | function | Projects handler rows, redacts credential-named values, returns receipt |
Submodules pinning and shaping are imported explicitly; gateway.__init__ exports no names.
Clients (recohut_kit.mcp.clients)
| Name | Kind | What it does |
|---|---|---|
RegistryRecord | dataclass | One registry entry parsed from server JSON |
ResolutionPolicy | dataclass | Pin versions, trusted runtimes, allowlists for runtime args and env names |
Refusal | dataclass | Named refusal with reason when resolution fails policy |
resolve | function | Resolves a record to StdioConfig, HttpConfig, or Refusal without executing |
NamespacePolicy | dataclass | Per-server tool naming rule |
namespaced | function | Builds a model-compatible namespaced tool name (max 64 characters) |
collision_check | function | Detects duplicate tool names across selected server inventories |
RootsPolicy, validate_root | dataclass, function | Filesystem root allowlisting for client roots capability |
ElicitationPolicy, validate_elicitation | types, function | ElicitationPolicy is a positive rate-limit record; validate_elicitation checks the flat form schema and the submitted content |
SamplingPolicy, RateLimiter | dataclass, class | SamplingPolicy maps sampling hints to a configured route; RateLimiter admits calls in a per-server, per-capability one-minute window |
ToolTranslator, InternalTool | class, dataclass | InternalTool.from_mcp copies an MCP tool into an internal record, and ToolTranslator emits a model-family tool envelope |
CachePolicy, AssemblyReceipt, ToolSearchPolicy | dataclasses | Tool list assembly policies and receipts |
OAuthClientConfig, TokenRecord | dataclasses | OAuth configuration records (no network I/O in-module) |
ClientChecklist, ChecklistRow | dataclasses | Client readiness checklist rows |
RetryDecision, SubscriptionState | dataclasses | Client recovery state records |
Hosts (recohut_kit.mcp.hosts)
| Name | Kind | What it does |
|---|---|---|
StdioConfig, HttpConfig | dataclasses | StdioConfig hides environment and HttpConfig hides headers; stdio args stay in the repr unless RegistryStdioConfig is used |
Capabilities, CapabilityFilter, FilterReceipt | dataclasses | Host capability filtering records |
ContentBlock, from_result, to_native_tool | types, functions | from_result maps a result wire's content array to content blocks, and to_native_tool turns a tool definition into a ToolSpec |
RetryPolicy, ErrorCode, reconnect receipts | dataclasses | Host retry policy and receipts |
ResourceRecord, SelectionPolicy, validate_selection | types | Record discovered resources and accept or reject a name selection |
PromptRecord, collect_arguments, RolePolicy | types | Prompt argument collection and role policy |
TurnBudget, HostTurn, TranscriptLedger, ModelAdapter | dataclasses, protocol | TurnBudget and HostTurn are frozen dataclasses, TranscriptLedger is a plain append-only class, and ModelAdapter is a Protocol with no provider import |
ModelReply | dataclass | Observable model reply shape for host loops |
Servers (recohut_kit.mcp.servers)
| Name | Kind | What it does |
|---|---|---|
ToolContract, ToolRouter, ToolBinding | dataclasses, class | Explicit tool contracts and name-to-handler routing |
ToolResult, ToolErrorResult | dataclasses | Result and contained-error result shapes |
PromptContract, PromptBinding, rubric helpers | dataclasses, functions | PromptContract and PromptBinding are prompt design records, and rubric_score returns static authoring diagnostics |
ResourceContract, TemplateContract, resource_source_issues | dataclasses, function | Resource and template records; resource_source_issues reports advisory AST write calls; URI scheme checks live in validate_scheme |
LifespanRecord, ListChange, ResourceUpdated | dataclasses | Server lifecycle change records |
InspectorSession, EvaluationCase, evaluation receipts | dataclasses | Server inspection and evaluation session records |
PrimitiveController, ServerApiChoice, TransportChoice | dataclasses | Server design choice records |
Capabilities (recohut_kit.mcp.capabilities)
| Name | Kind | What it does |
|---|---|---|
CursorSigner, Cursor, Page, InvalidCursor | class, dataclasses | HMAC-signed, revision-bound listing cursors over Continuation |
complete, CompletionPolicy, CompletionReceipt | function, dataclasses | Bounded completion paging with receipts |
detect, logging and notification policies | function, dataclasses | Capability detection and logging policy records |
ElicitationSchemaValidator, semantic_outcome, contains, safe_text | class, functions | contains checks whether a path is inside a named file root, and safe_text scrubs diagnostic text |
SpecVersionMatrix, SdkFeatureReport, session and sampling records | dataclasses | Capability and SDK observation records shared across owners |
How it composes
The root module pulls process_environment and require_timeout from recohut_kit._process and Registry from recohut_kit.plugins. stdio_session passes process_environment output to the child, and both SDK lines also add their restricted runtime defaults. Timeouts are validated before sessions open. MCPServer.register_plugins builds ToolRegistration values from an explicit name list in a plugin registry.
recohut_kit.mcp.gateway.shaping imports redaction markers, mask_text, and redact; capability policies and validation import markers and scrub_text. recohut_kit.mcp.capabilities.cursors uses recohut_kit.bounded.Continuation and recohut_kit.json canonical JSON helpers. Client registry resolution emits recohut_kit.mcp.hosts.transports.StdioConfig and HttpConfig. Host and capability modules import shared recohut_kit.mcp.protocol records and their own sibling modules; they do not import the other MCP subpackages.
Official mcp and fastmcp packages are imported lazily inside MCPServer.create, FastMCPServer.create, http_session, stdio_session, and client session setup. Compatibility helpers choose MCPServer versus FastMCP, streamable_http_client versus streamablehttp_client, and timedelta versus numeric read timeouts by inspecting installed symbols, not by parsing version strings.
Minimal usage
Install the mcp extra from your Kit checkout with uv pip install '.[mcp]'. This example runs a local stdio server in the same Python environment and reads a fixed greeting.
import sys
from pathlib import Path
from tempfile import TemporaryDirectory
from recohut_kit.mcp import call_tool_sync, result_is_error, result_wire, stdio_session
server_source = """
from recohut_kit.mcp import MCPServer, ToolRegistration
def greeting() -> str:
return "Hello from the local MCP server."
server = MCPServer.create(name="kit-reference")
server.register([ToolRegistration(greeting, "greeting")])
server.run("stdio")
"""
with TemporaryDirectory() as directory:
script = Path(directory) / "server.py"
script.write_text(server_source, encoding="utf-8")
session = stdio_session(
command=sys.executable, args=[str(script)], environment={}, cwd=directory,
)
result = call_tool_sync(session, "greeting", {})
assert not result_is_error(result)
assert result_wire(result)["content"][0]["text"] == "Hello from the local MCP server."The caller supplies the command, working directory, and environment overrides. result_wire and result_is_error give callers the same result inspection across the supported SDK lines.
Limits and gotchas
- Importing
recohut_kit.mcpdoes not import the official SDK; missingmcpfails only when you open a session or create a server. MCPServer.createwithversion=on MCP 1.x raisesValueErrorwhen the low-level server exposes no version field; use 2.x or omitversion.runaccepts onlystdioorstreamable-http; other transport strings raiseValueError.http_sessionrequires positivetimeout_secondsand performs no implicit authentication; headers are caller-owned.stdio_sessionfilters environment throughprocess_environment, is not a sandbox, and does not cap overall session lifetime beyond native read timeouts.call_tool_syncraisesRuntimeErrorinside a running event loop; useasync withandawait client.callinstead.- Native
CallToolResultfields differ (isErrorversusis_error); useresult_wireandresult_is_errorfor portable checks. - Registry
runtimeArgumentsare passed through only when the name is allowlisted and the value fully matches that name's regex. Registry environment values are ignored unless the name is allowlisted and the entry is not marked secret. Unpinned package versions refuse withpackage_version_not_pinned. gateway.shapingredacts credential-named fields and optional string masking; it is not PII detection. Required evidence fields cannot also be listed for redaction.gateway.pinningfingerprints published tool metadata only; the host must store approved pins and enforce policy on drift.hosts.hostdefinesModelAdapteras a Protocol for integrators; this package does not call a model itself.- Server and host package entries are dependency-free of the MCP SDK; client registry, recovery, and translation import host transport, retry, and content types. Stdio and Streamable HTTP wire sessions live in the root module; host turn contracts define
ModelAdapterand do not import a provider SDK.
Verification
The example checks a fixed response from a local stdio server. See Verify the examples.
How is this page?
Last updated on