Skip to Content
Recodocs

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.

9 min read

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)

NameKindWhat it does
ToolRegistrationdataclassTrusted native callable; SDK annotations define its input schema
ToolServerprotocolregister tools and unwrap the native server
ToolClientprotocolcall a tool by name and unwrap the native session
Transporttype alias"stdio" or "streamable-http"
MCPServerclassWraps the official SDK server; create, run, register, register_plugins, unwrap
FastMCPServerclassSubclasses MCPServer, registers through FastMCP tool(), and create always builds fastmcp.FastMCP while holding host and port for run
MCPClientclassWraps a native session; call returns the native CallToolResult unchanged
result_wirefunctionJSON wire view of a native result with camelCase keys on both SDK lines
result_is_errorfunctionReads isError from that wire view for 1.x and 2.x
http_sessionasync context managerOpens Streamable HTTP; caller supplies headers; no implicit auth
stdio_sessionasync context managerSpawns stdio child with process_environment; caller authorizes command and env
call_tool_syncfunctionOne-shot sync tool call; refuses inside a running event loop

Protocol (recohut_kit.mcp.protocol)

NameKindWhat it does
IconRecorddataclassApplication-selected icon metadata; icon source grants no filesystem access
ServerInfodataclassServer identity fields observed from initialize; excludes arbitrary settings
PromptArgumentdataclassOne prompt argument; required defaults false per MCP schema

Gateway (recohut_kit.mcp.gateway)

NameKindWhat it does
tool_fingerprintfunctionStable SHA-256 over name, description, input schema, and behaviour hints
PinDiffdataclassAdded, changed, and removed tool names between pin sets
diff_pinsfunctionCompares pinned fingerprints to a fresh discovery keyed by tool name
ProjectiondataclassOrdered declared fields for a tool response shape
ProjectionRefusedexceptionRaised when requested names a field the tool did not declare
ShapingReceiptdataclassByte sizes, returned, dropped, and missing field names, and a redaction count; not the dropped or redacted values
shapefunctionProjects 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)

NameKindWhat it does
RegistryRecorddataclassOne registry entry parsed from server JSON
ResolutionPolicydataclassPin versions, trusted runtimes, allowlists for runtime args and env names
RefusaldataclassNamed refusal with reason when resolution fails policy
resolvefunctionResolves a record to StdioConfig, HttpConfig, or Refusal without executing
NamespacePolicydataclassPer-server tool naming rule
namespacedfunctionBuilds a model-compatible namespaced tool name (max 64 characters)
collision_checkfunctionDetects duplicate tool names across selected server inventories
RootsPolicy, validate_rootdataclass, functionFilesystem root allowlisting for client roots capability
ElicitationPolicy, validate_elicitationtypes, functionElicitationPolicy is a positive rate-limit record; validate_elicitation checks the flat form schema and the submitted content
SamplingPolicy, RateLimiterdataclass, classSamplingPolicy maps sampling hints to a configured route; RateLimiter admits calls in a per-server, per-capability one-minute window
ToolTranslator, InternalToolclass, dataclassInternalTool.from_mcp copies an MCP tool into an internal record, and ToolTranslator emits a model-family tool envelope
CachePolicy, AssemblyReceipt, ToolSearchPolicydataclassesTool list assembly policies and receipts
OAuthClientConfig, TokenRecorddataclassesOAuth configuration records (no network I/O in-module)
ClientChecklist, ChecklistRowdataclassesClient readiness checklist rows
RetryDecision, SubscriptionStatedataclassesClient recovery state records

Hosts (recohut_kit.mcp.hosts)

NameKindWhat it does
StdioConfig, HttpConfigdataclassesStdioConfig hides environment and HttpConfig hides headers; stdio args stay in the repr unless RegistryStdioConfig is used
Capabilities, CapabilityFilter, FilterReceiptdataclassesHost capability filtering records
ContentBlock, from_result, to_native_tooltypes, functionsfrom_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 receiptsdataclassesHost retry policy and receipts
ResourceRecord, SelectionPolicy, validate_selectiontypesRecord discovered resources and accept or reject a name selection
PromptRecord, collect_arguments, RolePolicytypesPrompt argument collection and role policy
TurnBudget, HostTurn, TranscriptLedger, ModelAdapterdataclasses, protocolTurnBudget and HostTurn are frozen dataclasses, TranscriptLedger is a plain append-only class, and ModelAdapter is a Protocol with no provider import
ModelReplydataclassObservable model reply shape for host loops

Servers (recohut_kit.mcp.servers)

NameKindWhat it does
ToolContract, ToolRouter, ToolBindingdataclasses, classExplicit tool contracts and name-to-handler routing
ToolResult, ToolErrorResultdataclassesResult and contained-error result shapes
PromptContract, PromptBinding, rubric helpersdataclasses, functionsPromptContract and PromptBinding are prompt design records, and rubric_score returns static authoring diagnostics
ResourceContract, TemplateContract, resource_source_issuesdataclasses, functionResource and template records; resource_source_issues reports advisory AST write calls; URI scheme checks live in validate_scheme
LifespanRecord, ListChange, ResourceUpdateddataclassesServer lifecycle change records
InspectorSession, EvaluationCase, evaluation receiptsdataclassesServer inspection and evaluation session records
PrimitiveController, ServerApiChoice, TransportChoicedataclassesServer design choice records

Capabilities (recohut_kit.mcp.capabilities)

NameKindWhat it does
CursorSigner, Cursor, Page, InvalidCursorclass, dataclassesHMAC-signed, revision-bound listing cursors over Continuation
complete, CompletionPolicy, CompletionReceiptfunction, dataclassesBounded completion paging with receipts
detect, logging and notification policiesfunction, dataclassesCapability detection and logging policy records
ElicitationSchemaValidator, semantic_outcome, contains, safe_textclass, functionscontains checks whether a path is inside a named file root, and safe_text scrubs diagnostic text
SpecVersionMatrix, SdkFeatureReport, session and sampling recordsdataclassesCapability 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.mcp does not import the official SDK; missing mcp fails only when you open a session or create a server.
  • MCPServer.create with version= on MCP 1.x raises ValueError when the low-level server exposes no version field; use 2.x or omit version.
  • run accepts only stdio or streamable-http; other transport strings raise ValueError.
  • http_session requires positive timeout_seconds and performs no implicit authentication; headers are caller-owned.
  • stdio_session filters environment through process_environment, is not a sandbox, and does not cap overall session lifetime beyond native read timeouts.
  • call_tool_sync raises RuntimeError inside a running event loop; use async with and await client.call instead.
  • Native CallToolResult fields differ (isError versus is_error); use result_wire and result_is_error for portable checks.
  • Registry runtimeArguments are 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 with package_version_not_pinned.
  • gateway.shaping redacts credential-named fields and optional string masking; it is not PII detection. Required evidence fields cannot also be listed for redaction.
  • gateway.pinning fingerprints published tool metadata only; the host must store approved pins and enforce policy on drift.
  • hosts.host defines ModelAdapter as 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 ModelAdapter and 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