intellicrack.mcp
Model Context Protocol client for Intellicrack.
Third-party MCP servers appear inside Intellicrack as ordinary tools: they are configured in mcp.json, connected over stdio or
Streamable HTTP, and registered into the same tool registry the built-in bridges use, so the orchestrator, the confirmation dialog and the
chat transcript treat them exactly as they treat Ghidra or Frida.
What is deliberately different is trust. A bridge ships with the application; a server does not. Nothing local is launched without the operator seeing the exact command first, a server’s claims about its own tools count for nothing until the operator marks it trusted, and every piece of text a server sends is bounded and fenced before it reaches the model.
This package imports no Qt and is importable headless. The dialogs that ask the operator anything live under intellicrack.ui, and
reach this package through the callables it accepts.
- class ApprovalRecord[source]
Bases:
objectOne remembered answer to a tool confirmation.
- Variables:
namespace (str) – The tool namespace, e.g.
mcp-files.function_name (str) – The canonical dotted function name.
generation (str) – The key the answer was given about: for a server’s tool, the
approval_binding()of its tool-listing generation and its identity. Empty for an answer recorded without one, which no longer applies to anything.approved (bool) –
Truefor an approval,Falsefor a refusal.scope (ApprovalScope) – How long the answer lasts.
- namespace: str
- function_name: str
- generation: str
- approved: bool
- scope: ApprovalScope
- property identity: str
The server identity the answer is bound to.
- Returns:
The identity, or an empty string for an answer recorded before approvals were bound to identity, which no longer applies to anything.
- Return type:
- __init__(namespace, function_name, generation, approved, scope)
- Parameters:
namespace (str)
function_name (str)
generation (str)
approved (bool)
scope (ApprovalScope)
- Return type:
None
- class ApprovalScope[source]
Bases:
EnumHow long an operator’s answer to a tool confirmation lasts.
- Variables:
ONCE – Applies to this call only; nothing is recorded.
SESSION – Applies until the application exits.
ALWAYS – Persisted, and survives a restart until the server’s tool listing changes.
- ONCE = 'once'
- SESSION = 'session'
- ALWAYS = 'always'
- class ApprovalStore[source]
Bases:
objectPer-tool approvals, keyed by namespace, function name and approval key.
sessionanswers live in memory for the life of the process.alwaysanswers are persisted. For a server’s tool the key is theapproval_binding()of the server’s tool-listing generation and its identity, so an answer never carries over to a tool whose definition has changed underneath it, nor to a different program or endpoint that took over the server’s id.- __init__(path=None)[source]
Initialize the store.
- Parameters:
path (Path | None) – File to persist
alwaysanswers to. Defaults to<config_dir>/mcp_approvals.json.- Return type:
None
- property path: Path
Location of the file this store persists to.
- Returns:
The approvals file path.
- Return type:
Path
- decision(namespace, function_name, generation)[source]
Look up a remembered answer.
- Parameters:
- Returns:
Truefor a remembered approval,Falsefor a remembered refusal,Nonewhen the operator must be asked.- Return type:
bool | None
- remember(namespace, function_name, generation, *, approved, scope)[source]
Record an operator’s answer for the requested duration.
- Parameters:
namespace (str) – The server namespace.
function_name (str) – The canonical dotted function name.
generation (str) – The server’s current tool-listing generation.
approved (bool) – The operator’s answer.
scope (ApprovalScope) – How long the answer applies.
- Raises:
ValueError – If an
alwaysanswer is given without a generation. Such an answer could never be invalidated, so it would outlive any change to what the tool does.- Return type:
None
A file that cannot be read or written propagates
McpConsentStoreError; the answer then lasts this session only, and the file is left untouched.
- invalidate_namespace(namespace)[source]
Drop every remembered answer belonging to one server.
Called when a server’s tool listing changes, so the operator is asked again about tools they had already answered for.
- Parameters:
namespace (str) – The server namespace to clear.
- Return type:
None
- clear_session()[source]
Drop every
sessionanswer, leaving persisted ones in place.- Return type:
None
- entries()[source]
List every remembered answer, session-scoped and persisted.
- Returns:
The answers, session ones first, each group sorted by key.
- Return type:
- revoke(namespace, function_name, generation)[source]
Forget one remembered answer, in every scope it was kept in.
- class ConsentAnswer[source]
Bases:
objectThe operator’s full answer to a launch-consent prompt.
- Variables:
approved (bool) – Whether this launch may go ahead.
trusted (bool) – Whether the operator also vouched for the server’s claims about its own tools. Meaningful only with
approved.blocked (bool) – Whether the operator asked never to be asked about this server again, refusing it until the refusal is reset in MCP Settings. A plain refusal leaves the next start free to ask.
- approved: bool
- trusted: bool
- blocked: bool
- class ContextTool[source]
Bases:
StrEnumOne function a server’s resources and prompts are reached through.
- Variables:
LIST_RESOURCES – List one page of resources.
LIST_RESOURCE_TEMPLATES – List one page of resource templates.
READ_RESOURCE – Read one resource.
LIST_PROMPTS – List one page of prompts.
GET_PROMPT – Fetch one prompt with its arguments filled in.
COMPLETE – Suggest values for one argument.
SUBSCRIBE_RESOURCE – Be told when a resource changes.
UNSUBSCRIBE_RESOURCE – Stop being told.
- LIST_RESOURCES = 'context.list_resources'
- LIST_RESOURCE_TEMPLATES = 'context.list_resource_templates'
- READ_RESOURCE = 'context.read_resource'
- LIST_PROMPTS = 'context.list_prompts'
- GET_PROMPT = 'context.get_prompt'
- COMPLETE = 'context.complete'
- SUBSCRIBE_RESOURCE = 'context.subscribe_resource'
- UNSUBSCRIBE_RESOURCE = 'context.unsubscribe_resource'
- __new__(value)
- class DangerousPattern[source]
Bases:
objectOne reason a proposed launch deserves a second look.
- Variables:
- token: str
- reason: str
- class HttpServerSpec[source]
Bases:
objectConnection description for a server reached over HTTP.
- Variables:
url (str) – Endpoint URL. Must be
httporhttps.headers (Mapping[str, str]) – Extra request headers. Values may carry
${input:id}references.query (Mapping[str, str]) – Query parameters composed onto
url, which is how several hosted servers carry an API key or a tool-set selection.oauth_client_id (str | None) – Pre-registered OAuth client id, or
None.oauth_metadata_url (str | None) – HTTPS URL of a Client ID Metadata Document, used as the client id when the authorization server supports CIMD.
- url: str
- exception McpAuthError[source]
Bases:
McpErrorAuthorization against an HTTP server failed or is unavailable.
Raised when the keyring backing per-server tokens is unusable, when an issuer check rejects stored credentials, and when an interactive sign-in cannot be completed.
- class McpClientHooks[source]
Bases:
objectThe callbacks one connection installs on its SDK client.
- Variables:
sampling (SamplingFnT | None) – Answers
sampling/createMessage, orNonewhen the server may not sample through Intellicrack, in which case thesamplingcapability is not advertised.sampling_capabilities (SamplingCapability | None) – The sampling sub-capabilities advertised with
sampling, such as tool use.list_roots (ListRootsFnT | None) – Answers
roots/list, orNoneto advertise no roots.logging (LoggingFnT | None) – Receives the server’s
notifications/messagelog records.
- sampling: SamplingFnT | None
- sampling_capabilities: SamplingCapability | None
- list_roots: ListRootsFnT | None
- logging: LoggingFnT | None
- __init__(sampling=None, sampling_capabilities=None, list_roots=None, logging=None)
- Parameters:
sampling (SamplingFnT | None)
sampling_capabilities (SamplingCapability | None)
list_roots (ListRootsFnT | None)
logging (LoggingFnT | None)
- Return type:
None
- class McpConfigDocument[source]
Bases:
objectThe parsed contents of
mcp.json.- Variables:
servers (tuple[McpServerConfig, ...]) – Configured servers, in file order.
inputs (tuple[McpInputSpec, ...]) – Declared inputs, in file order.
rejected (tuple[McpRejectedServer, ...]) – Server entries that could not be used, each with its reason. One bad entry never costs the operator the others.
- servers: tuple[McpServerConfig, ...]
- inputs: tuple[McpInputSpec, ...]
- rejected: tuple[McpRejectedServer, ...]
- server(server_id)[source]
Look up one configured server by id.
- Parameters:
server_id (str) – The id to resolve.
- Returns:
The server, or
Nonewhen absent.- Return type:
McpServerConfig | None
- __init__(servers=(), inputs=(), rejected=())
- Parameters:
servers (tuple[McpServerConfig, ...])
inputs (tuple[McpInputSpec, ...])
rejected (tuple[McpRejectedServer, ...])
- Return type:
None
- input_spec(input_id)[source]
Look up one declared input by id.
- Parameters:
input_id (str) – The id to resolve.
- Returns:
The input, or
Nonewhen absent.- Return type:
McpInputSpec | None
- with_server(config)[source]
Return a copy with one server added or replaced.
- Parameters:
config (McpServerConfig) – The server to store.
- Returns:
The updated document.
- Return type:
- without_server(server_id)[source]
Return a copy with one server removed.
- Parameters:
server_id (str) – The id to remove.
- Returns:
The updated document.
- Return type:
- with_input(spec)[source]
Return a copy with one input declaration added or replaced.
- Parameters:
spec (McpInputSpec) – The input declaration to store.
- Returns:
The updated document.
- Return type:
- exception McpConfigError[source]
Bases:
McpErrorA server configuration is malformed, unsafe, or unresolvable.
Raised for a bad
serverId, a literal secret written intomcp.json, an unresolvable${input:id}reference, and shell metacharacters in a launch command.
- class McpConfigStore[source]
Bases:
objectReads and writes
mcp.json.The store owns the file’s location and its two accepted root shapes. It performs no I/O in its constructor, so a caller can build one to parse an imported document without touching the configured path.
- __init__(path=None)[source]
Initialize the store.
- Parameters:
path (Path | None) – Configuration file to read and write. Defaults to
<config_dir>/mcp.json.- Return type:
None
- property path: Path
Location of the configuration file this store manages.
- Returns:
The configuration file path.
- Return type:
Path
- load()[source]
Read and parse the configuration file.
A missing file is an empty configuration rather than an error, which is the state every installation starts in.
- Returns:
The parsed document.
- Return type:
- Raises:
McpConfigError – If the file cannot be read, is not valid JSON, or fails validation.
- save(document)[source]
Write a configuration document to disk.
The file is written through a sibling temporary file and replaced atomically, so an interrupted write cannot leave a truncated configuration behind.
- Parameters:
document (McpConfigDocument) – The document to persist.
- Raises:
McpConfigError – If a server fails validation or the file cannot be written.
- Return type:
None
- import_document(raw)[source]
Parse a configuration document from JSON text.
Server entries that cannot be used are reported in
McpConfigDocument.rejectedand the rest are imported.- Parameters:
raw (str) – JSON text in either the
serversormcpServersshape.- Returns:
The parsed document.
- Return type:
- Raises:
McpConfigError – If the text is not valid JSON, the decoded document fails validation, or it declares servers and not one of them can be used.
- static parse_document(data, *, retain_rejected=False)[source]
Parse an already-decoded configuration document.
Both accepted roots are normalized here:
serversis the native shape andmcpServersis the shape other clients write. A document carrying both is refused rather than silently merged. A server entry that cannot be used is set aside inMcpConfigDocument.rejectedwith its reason, and the others are kept.- Parameters:
- Returns:
The parsed document.
- Return type:
- Raises:
McpConfigError – If both roots are present, a root has the wrong type, or an input entry is malformed or repeats an id.
- static serialize_document(document)[source]
Render a configuration document to its JSON shape.
Set-aside server entries marked as retained are written back exactly as they were read. One whose key a usable server now holds – the operator renamed a server onto it – is written under the next free numbered key instead, so neither overwrites the other.
- Parameters:
document (McpConfigDocument) – The document to render.
- Returns:
The JSON root, always in the native
serversshape.- Return type:
- exception McpConnectionError[source]
Bases:
McpErrorA server could not be reached, or an established connection dropped.
- exception McpConsentDeniedError[source]
Bases:
McpErrorThe operator refused consent for an action that requires it.
Raised before a local server process is spawned when the consent gate reports refusal, so nothing is launched.
- class McpConsentGate[source]
Bases:
objectDecides whether a local server may be launched, asking when it must.
A gate is consulted before anything is spawned. It answers from a recorded decision when the launch is byte-identical to one already approved, and otherwise asks – which, headless, means refusing, because no prompt is available to ask through.
- __init__(trust, prompt, on_generation_change=None, on_identity_change=None)[source]
Initialize the gate.
- Parameters:
trust (TrustStore) – Store holding trust state and approved launches.
prompt (LaunchPrompt) – Callable that presents the launch and returns the operator’s answer.
on_generation_change (Callable[[str, str], None] | None) – Invoked with the server id and its new generation whenever a server’s tool listing changes. This is where remembered per-tool approvals are discarded, so an answer about the old definitions is never replayed against the new ones.
on_identity_change (Callable[[str], None] | None) – Invoked with the server id whenever the program or endpoint a server id names, or what it may reach, is no longer the one the operator judged. Remembered per-tool approvals are discarded here too.
- Return type:
None
- property trust: TrustStore
The trust store this gate reads and writes.
- Returns:
The backing store.
- Return type:
- set_prompt(prompt)[source]
Replace the callable that asks the operator.
- Parameters:
prompt (LaunchPrompt) – The new prompt.
deny_all_launches()is the one to install once nobody is left to ask, such as while the application shuts down.- Return type:
None
- set_config_lookup(lookup)[source]
Install how the gate finds a server’s current configuration.
Trust is recorded against a server’s identity as well as its id. With a lookup installed,
is_trusted()honours a record only while the id still names the program or endpoint it was given to.- Parameters:
lookup (Callable[[str], McpServerConfig | None] | None) – Returns the configuration for a server id, or
Nonewhen no such server is configured.Noneremoves the lookup, leaving trust keyed by id alone.- Return type:
None
- async ensure_launch_consent(config, env)[source]
Obtain consent to launch a local server, or refuse.
- Parameters:
config (McpServerConfig) – The server about to be launched.
env (Mapping[str, str]) – The fully resolved environment the child would receive.
- Raises:
McpConsentDeniedError – If the server is marked denied, if it has no launch description, or if the operator refuses.
- Return type:
None
- record_answer(config, env, answer)[source]
Apply the operator’s answer about one proposed launch.
An approval records the exact launch, so the same launch is not asked about again. Trust follows the answer: ticking the trust box grants it, and approving a launch that differs from the one approved before without ticking it withdraws trust given about the old launch. A plain refusal records nothing, so the next start asks again; only an explicit never-ask-again marks the server denied.
- Parameters:
config (McpServerConfig) – The server the answer is about.
env (Mapping[str, str]) – The resolved environment the answer was given about.
answer (ConsentAnswer) – The operator’s answer.
- Returns:
Truewhen the launch was approved.- Return type:
- Raises:
McpConsentDeniedError – If the server has no launch description.
- note_identity(config)[source]
Check that a server id still names the server the operator judged.
Runs before every connection, whatever the transport: a remote server never passes through launch consent, and its headers or its OAuth client can change as surely as a local server’s command. A record made about another identity is discarded – trust, refusal, approved launch and remembered tool approvals alike – so the operator is asked again. A server with no identity on record has it recorded, so a later change is noticed.
- Parameters:
config (McpServerConfig) – The server as currently configured.
- Returns:
Truewhen the identity had changed and the record was discarded.- Return type:
A trust file that cannot be read or written propagates
McpConsentStoreError.
- note_generation(server_id, generation)[source]
Record a server’s current tool listing and report whether it moved.
- class McpContextChange[source]
Bases:
StrEnumWhat changed.
- Variables:
RESOURCES_LISTED – The server’s list of resources changed.
PROMPTS_LISTED – The server’s list of prompts changed.
RESOURCE_UPDATED – A resource the client subscribed to was updated.
- RESOURCES_LISTED = 'resources_listed'
- PROMPTS_LISTED = 'prompts_listed'
- RESOURCE_UPDATED = 'resource_updated'
- __new__(value)
- class McpContextEvent[source]
Bases:
objectOne change a server announced.
- Variables:
server_id (str) – The server.
change (McpContextChange) – What changed.
uri (str | None) – The updated resource’s URI exactly as the server sent it, for
McpContextChange.RESOURCE_UPDATED;Noneotherwise.
- server_id: str
- change: McpContextChange
- __init__(server_id, change, uri=None)
- Parameters:
server_id (str)
change (McpContextChange)
uri (str | None)
- Return type:
None
- type McpContextListener = Callable[[McpContextEvent], None]
- exception McpError[source]
Bases:
IntellicrackErrorBase class for every Model Context Protocol failure.
- type McpHooksFactory = Callable[[McpServerConfig], McpClientHooks]
- class McpInputSpec[source]
Bases:
objectOne value the operator is prompted for and the keyring then holds.
- Variables:
- id: str
- description: str
- password: bool
- class McpLogRecord[source]
Bases:
objectOne log message a server sent, cleaned for display.
- Variables:
- received_at: datetime
- server_id: str
- level: str
- text: str
- render()[source]
Render the record as one line of the settings view.
- Returns:
time level [logger] text.- Return type:
- exception McpProtocolError[source]
Bases:
McpErrorA server violated the protocol contract it advertised.
Raised when a tool result fails the
outputSchemathe server itself published, and for a tool listing that cannot be interpreted.
- class McpRootsSpec[source]
Bases:
objectWhich folders a server is told it may work in, answered to
roots/list.How the roots are put together is set out in
intellicrack.mcp.roots.- Variables:
enabled (bool) – Whether the server is offered roots at all. Off withdraws the
rootscapability, so the server is never asked.include_session (bool) – Whether the active session’s folders – the target binary’s, the other binaries’, and those the operator added – are among them.
folders (tuple[str, ...]) – Absolute folders offered to this server only.
exclude (tuple[str, ...]) – Absolute session folders this server is not told about. A sandboxed server is always told about its
allowWritedirectories, whatever this says.
- enabled: bool
- include_session: bool
- class McpSandboxSpec[source]
Bases:
objectConfinement applied to a local server process on Windows.
What each field actually enforces is set out in
intellicrack.mcp.sandbox_launch.- Variables:
enabled (bool) – Whether the child is created suspended inside a job object, with a restricted Low integrity token and an allowlisted environment, before it runs.
allow_write (tuple[str, ...]) – Absolute directories the child may create files and folders in. For as long as the server runs each one carries a Low mandatory label that new content inherits; the label is removed again when the server stops. Everything the operator owns outside them stays unwritable to the child, apart from locations Windows itself labels Low such as
AppData/LocalLow. Reads are not restricted.allowed_domains (tuple[str, ...]) – Hostnames the operator expects the child to reach. Recorded and logged only: it is not enforced, and a sandboxed server can still connect to any host.
inherit_env (tuple[str, ...]) – Names of further variables from Intellicrack’s own environment the child keeps, beyond the fixed allowlist in
intellicrack.mcp.sandbox_launch. Nothing is inherited by default that could carry a credential; a name listed here is the operator’s deliberate choice.write_existing (bool) – Whether files and folders already inside the
allow_writedirectories may be changed too. Off by default, so a server can add to a directory without being able to alter what was there before it started; either way every label is reverted when the server stops.
- enabled: bool
- write_existing: bool
- class McpSecretResolver[source]
Bases:
objectExpands
${input:id}references from the credential store.One resolver serves every configured server. Values are read on demand rather than cached, so a credential rotated in the keyring takes effect on the next connection without restarting the application.
- __init__(store)[source]
Initialize the resolver.
- Parameters:
store (CredentialStore) – Credential store holding each input’s value.
- Return type:
None
- property store: CredentialStore
The credential store this resolver reads and writes.
- Returns:
The backing store.
- Return type:
- async resolve(template)[source]
Expand every
${input:id}reference in one configuration value.- Parameters:
template (str) – The raw configuration value.
- Returns:
templatewith each reference replaced by its stored value. A value carrying no reference is returned unchanged without touching the keyring.- Return type:
A referenced input with no stored value propagates
McpConfigError, and an unusable keyring propagatesMcpAuthError, both fromresolve_input().
- async resolve_mapping(values)[source]
Expand references across a whole environment or header mapping.
- Parameters:
values (Mapping[str, str]) – Raw configuration values keyed by field name.
- Returns:
The same keys with every value expanded.
- Return type:
- Raises:
McpConfigError – If a referenced input has no stored value. The message names the field so the operator knows which entry to fix.
- async resolve_sequence(values, *, field)[source]
Expand references across an ordered list such as launch arguments.
- Parameters:
- Returns:
The same values, in order, each expanded.
- Return type:
- Raises:
McpConfigError – If a referenced input has no stored value. The message names the position so the operator knows which entry to fix.
- async set_input(input_id, value)[source]
Store one input’s value in the keyring.
- Parameters:
- Raises:
McpAuthError – If the keyring is unusable, so nothing was stored.
- Return type:
None
- async delete_input(input_id)[source]
Remove one input’s stored value.
- Parameters:
input_id (str) – The input declaration’s identifier.
- Returns:
Truewhen a value was removed,Falsewhen none was stored.- Return type:
- Raises:
McpAuthError – If the keyring is unusable, so nothing could be removed.
- async has_input(input_id)[source]
Report whether an input currently has a stored value.
- Parameters:
input_id (str) – The input declaration’s identifier.
- Returns:
Truewhen a non-empty value is stored.- Return type:
- Raises:
McpAuthError – If the keyring is unusable, so the answer is unknown. An unknown answer is never reported as
False, which would let a caller conclude the operator simply has not entered the value yet.
- class McpServerConfig[source]
Bases:
objectEverything needed to reach one configured server.
- Variables:
server_id (str) – Identifier matching
SERVER_ID_PATTERN.kind (McpTransportKind) – Transport the server is reached over.
stdio (StdioServerSpec | None) – Launch description when
kindisMcpTransportKind.STDIO.http (HttpServerSpec | None) – Connection description when
kindisMcpTransportKind.HTTPorMcpTransportKind.SSE.enabled (bool) – Whether the server participates at all. Off until the operator turns it on.
disabled_tools (frozenset[str]) – Tool names, as the server publishes them, that are withheld from the model even while the server is enabled.
sandbox (McpSandboxSpec) – Confinement applied to a local server process.
request_timeout_s (float) – Per-call timeout in seconds.
log_level (str | None) – The lowest severity of the server’s own log messages Intellicrack asks for, one of
SERVER_LOG_LEVELS, orNoneto ask for none on a 2026-07-28 connection and leave the server’s default on an earlier one.roots (McpRootsSpec) – The folders the server is told it may work in.
- server_id: str
- kind: McpTransportKind
- stdio: StdioServerSpec | None
- http: HttpServerSpec | None
- enabled: bool
- sandbox: McpSandboxSpec
- request_timeout_s: float
- roots: McpRootsSpec
- property is_http: bool
Whether the server is reached over HTTP rather than a child process.
- Returns:
Truefor the HTTP and SSE transports.- Return type:
- validate()[source]
Check every invariant the rest of the client relies on.
- Raises:
McpConfigError – If the id is malformed, the transport block does not match the declared kind, a URL is not HTTP, the timeout is out of range, OAuth is configured on a local server, a sandbox write path is not absolute, or a literal credential was written into the file.
- Return type:
None
- input_ids()[source]
List every input id this server’s values reference.
- __init__(server_id, kind, stdio=None, http=None, enabled=False, disabled_tools=frozenset({}), sandbox=McpSandboxSpec(enabled=False, allow_write=(), allowed_domains=(), inherit_env=(), write_existing=False), request_timeout_s=60.0, log_level=None, roots=McpRootsSpec(enabled=True, include_session=True, folders=(), exclude=()))
- Parameters:
server_id (str)
kind (McpTransportKind)
stdio (StdioServerSpec | None)
http (HttpServerSpec | None)
enabled (bool)
sandbox (McpSandboxSpec)
request_timeout_s (float)
log_level (str | None)
roots (McpRootsSpec)
- Return type:
None
- class McpServerLogBook[source]
Bases:
objectReceives every server’s log messages and keeps each server’s recent ones.
Callbacks are invoked on the MCP event loop and listeners are called there too; a GUI listener must hand the record to its own thread.
- __init__(*, capacity=500, rate_per_s=20.0, burst=100, clock=<built-in function monotonic>)[source]
Create an empty log book.
- callback_for(server_id)[source]
Build the SDK logging callback for one server.
- Parameters:
server_id (str) – The server the callback receives messages from.
- Returns:
The callback.
- Return type:
LoggingFnT
- receive(server_id, level, logger, data)[source]
Log, keep and announce one message, unless the server is over its rate.
- Parameters:
- Returns:
The record, or
Nonewhen it was rate limited.- Return type:
McpLogRecord | None
- records(server_id)[source]
Return a server’s recent records.
- Parameters:
server_id (str) – The server.
- Returns:
Its records, oldest first.
- Return type:
- suppressed(server_id)[source]
Report how many of a server’s records are being held back by its rate limit.
- add_listener(listener)[source]
Call a function for every record kept from now on.
- Parameters:
listener (Callable[[McpLogRecord], None]) – Receives each record, on the MCP event loop.
- Return type:
None
- remove_listener(listener)[source]
Stop calling a listener.
- Parameters:
listener (Callable[[McpLogRecord], None]) – A listener added earlier.
- Return type:
None
- class McpToolCatalog[source]
Bases:
objectA server’s tool listing at one point in time.
- Variables:
server_id (str) – The server this listing came from.
entries (tuple[McpToolEntry, ...]) – The tools, in the order the server returned them.
generation (str) – Digest over the listing, stable across processes.
fetched_at (datetime) – When the listing was retrieved.
ttl_ms (int | None) – The server’s freshness hint in milliseconds, or
None.cache_scope (str | None) – The server’s cache scope hint, or
None.
- server_id: str
- entries: tuple[McpToolEntry, ...]
- generation: str
- fetched_at: datetime
- is_fresh(now)[source]
Report whether this listing may still be reused.
A server that published no
ttlMsgets no implied freshness: the listing is treated as stale so the next request re-lists.
- entry(canonical_name)[source]
Look up one tool by its canonical name.
- Parameters:
canonical_name (str) –
mcp-<serverId>.<toolName>.- Returns:
The tool, or
Nonewhen this server does not publish it.- Return type:
McpToolEntry | None
- entry_by_name(tool_name)[source]
Look up one tool by the name the server publishes it under.
- Parameters:
tool_name (str) – The server’s own tool name.
- Returns:
The tool, or
Nonewhen absent.- Return type:
McpToolEntry | None
- property tool_count: int
Number of tools in this listing.
- Returns:
The entry count.
- Return type:
- class McpToolEntry[source]
Bases:
objectOne tool a server publishes.
- Variables:
name (str) – The tool name as the server published it, verbatim.
canonical_name (str) –
mcp-<serverId>.<name>, the name Intellicrack routes, classifies, confirms and persists under.title (str | None) – The server’s display title, or
None.description (str) – The server’s description, truncated to
MAX_DESCRIPTION_CHARS.input_schema (dict[str, Any]) – Raw JSON Schema 2020-12 for the arguments, exactly as the server sent it.
output_schema (dict[str, Any] | None) – Raw JSON Schema for structured output, or
Nonewhen the server publishes none.annotations (ToolAnnotations | None) – The server’s behavioural hints, or
None. These are untrusted unless the server is trusted, which is why classification consults the trust store before reading them.advertised_schema (SanitizedSchema) –
input_schemarewritten to be safe in front of a model, with the aliases that map a call’s arguments back. Derived frominput_schemawhen the entry is built.
- name: str
- canonical_name: str
- description: str
- annotations: ToolAnnotations | None
- advertised_schema: SanitizedSchema
- __post_init__()[source]
Derive the schema the model is shown from the one the server published.
- Return type:
None
- property display_name: str
Human-facing label for this tool.
- Returns:
The server’s title when it published one, else its name.
- Return type:
- property read_only_hint: bool
The server’s own claim that this tool does not mutate state.
- Returns:
Trueonly when the server explicitly said so. Never consult this without first establishing the server is trusted.- Return type:
- property destructive_hint: bool
The server’s own claim that this tool performs destructive updates.
- Returns:
Truewhen the server explicitly said so.- Return type:
- class McpToolSource[source]
Bases:
objectRegisters every connected server’s tools into the tool registry.
One executor is registered per server namespace, alongside a definition provider the registry calls each time it is asked what tools exist. That indirection is what lets a server appear, disappear, or change its tool list without anything re-registering.
- __init__(manager, registry)[source]
Initialize the tool source.
- Parameters:
manager (McpConnectionManager) – The manager owning every server connection.
registry (ToolRegistry) – The tool registry to register namespaces into.
- Return type:
None
- property manager: McpConnectionManager
The connection manager this source reads from.
- Returns:
The manager.
- Return type:
- register_all()[source]
Register every configured server’s namespace into the registry.
A server is registered whether or not it is currently up: the namespace has to route before the connection exists, or a call arriving mid-reconnect would fail as an unknown tool rather than as a disconnected server. Every canonical name is also pushed through
to_wire_namehere, which warms the reverse registry before any history replay can need it.- Return type:
None
- unregister_all()[source]
Remove every namespace this source registered.
- Return type:
None
- context_tool_for(canonical_name)[source]
Resolve a canonical name to the resource or prompt function behind it.
- Parameters:
canonical_name (str) –
mcp-<serverId>.<name>.- Returns:
The function, or
Nonewhen the name is one of the server’s own tools or the server does not offer it.- Return type:
ContextTool | None
- note_context_event(event)[source]
Remember that a subscribed resource changed, until the model next reads it.
- Parameters:
event (McpContextEvent) – What the server announced.
- Return type:
None
- property updated_resources: list[tuple[str, str]]
The subscribed resources that changed since the model last read them.
- owns_namespace(namespace)[source]
Report whether a tool namespace belongs to a configured server.
- catalog_lines()[source]
Render the prompt section describing connected servers.
Only the servers themselves are listed – id, health, and how many tools each publishes – never the tools themselves. A large server would otherwise reintroduce the very prompt bloat dynamic loading exists to avoid, and the model reaches those tools through
tools.searchlike any other.Every fragment a server supplied is fenced, and the model is told plainly that what is inside the fence is data rather than instruction.
- entry_for(canonical_name)[source]
Resolve a canonical name back to the catalog entry behind it.
- Parameters:
canonical_name (str) –
mcp-<serverId>.<toolName>.- Returns:
The entry, or
Nonewhen no connected server publishes it.- Return type:
McpToolEntry | None
- generation_for(canonical_name)[source]
Read the tool-listing generation a canonical name belongs to.
Approvals are keyed by it, so a server that changes what its tools do invalidates the answers the operator gave about the old ones.
- approval_key_for(canonical_name)[source]
Build the key an operator’s answer about a call is remembered under.
- Parameters:
canonical_name (str) –
mcp-<serverId>.<toolName>.- Returns:
The
approval_binding()of the server’s tool-listing generation and its identity, orNonewhen the server is not connected or not configured.- Return type:
str | None
- is_read_only(canonical_name)[source]
Decide whether a call may skip destructive-operation confirmation.
A tool is read-only only when the operator has marked its server trusted and the server annotated the tool as read-only. An untrusted server’s annotations are its own claims about itself, and a hostile one would simply claim everything is harmless, so they buy it nothing.
- costs(server_id)[source]
Price every tool one server publishes.
- async execute(function_name, arguments, *, routed_server_id=None)[source]
Run one tool call, resolving its server from the canonical name.
This is the single dispatch path: every namespace the source registers routes through it. The server is always the one the canonical name itself names; a registry that routed the call by a different namespace is refused rather than silently delivering one server’s tool name to another server.
- Parameters:
- Returns:
The mapped result parts and the server’s error flag.
- Return type:
- Raises:
ToolError – If the name is not a well-formed MCP tool name, names a server other than the one it was routed to, or the call could not produce a usable result.
- class McpTransportKind[source]
Bases:
EnumTransport a configured server is reached over.
- Variables:
STDIO – A local child process speaking JSON-RPC over stdin/stdout.
HTTP – A remote endpoint speaking Streamable HTTP.
SSE – A remote endpoint declared with the legacy
ssetype, spoken to over the SDK’s HTTP+SSE client in itslegacyclient mode.
- STDIO = 'stdio'
- HTTP = 'http'
- SSE = 'sse'
- class SchemaViolation[source]
Bases:
objectOne way an instance failed its schema.
- Variables:
- path: str
- message: str
- __str__()[source]
Render the violation as one readable line.
- Returns:
<path>: <message>.- Return type:
- class StdioServerSpec[source]
Bases:
objectLaunch description for a local server started as a child process.
- Variables:
command (str) – Executable to run. Resolved without a shell.
args (tuple[str, ...]) – Arguments passed to
command, each one verbatim.cwd (str | None) – Working directory for the child, or
Noneto inherit.env (Mapping[str, str]) – Extra environment entries merged over the inherited environment. Values may carry
${input:id}references.env_file (str | None) – Path to a
KEY=VALUEfile whose entries are merged underenv, orNone.
- command: str
- class ToolCost[source]
Bases:
objectWhat advertising one tool costs in context.
- Variables:
- canonical_name: str
- schema_tokens: int
- description_tokens: int
- property total_tokens: int
Total context this tool occupies when advertised.
- Returns:
The sum of the schema and description costs.
- Return type:
- class TrustState[source]
Bases:
EnumHow far a server’s own claims may be believed.
- Variables:
UNTRUSTED – The default. Tool annotations are ignored and every call is treated as destructive.
TRUSTED – The operator vouched for this server. Its
readOnlyHintis honoured during classification.DENIED – The operator refused this server. It is never launched or connected.
- UNTRUSTED = 'untrusted'
- TRUSTED = 'trusted'
- DENIED = 'denied'
- class TrustStore[source]
Bases:
objectPer-server trust state, approved launches, and the last seen generation.
Persisted so an operator’s answer survives a restart, and reloaded on every read so an external edit to the file takes effect without restarting the application.
- __init__(path=None)[source]
Initialize the store.
- Parameters:
path (Path | None) – File to persist to. Defaults to
<config_dir>/mcp_trust.json.- Return type:
None
- property path: Path
Location of the file this store persists to.
- Returns:
The trust file path.
- Return type:
Path
- state(server_id)[source]
Read a server’s trust state.
- Parameters:
server_id (str) – The server to read.
- Returns:
The recorded state, defaulting to
TrustState.UNTRUSTED.- Return type:
- set_state(server_id, state, *, identity=None)[source]
Record a server’s trust state.
- Parameters:
server_id (str) – The server to update.
state (TrustState) – The state to record.
identity (str | None) – The
server_identity()of the server the operator judged, binding the record to it.Noneleaves the bound identity unchanged.
- Return type:
None
- identity(server_id)[source]
Read the identity a server’s record is bound to.
- belongs_to(config)[source]
Report whether a server’s record was made about this configuration.
- Parameters:
config (McpServerConfig) – The server as currently configured.
- Returns:
Falseonly when the record is bound to a different identity, meaning the id now names another program or endpoint.- Return type:
- state_for(config)[source]
Read a server’s trust state, honouring it only for the server it was given to.
- Parameters:
config (McpServerConfig) – The server as currently configured.
- Returns:
The recorded state when the record belongs to this configuration, and
TrustState.UNTRUSTEDwhen it was made about a different program or endpoint under the same id.- Return type:
- generation(server_id)[source]
Read the tool-listing generation last seen for a server.
- set_generation(server_id, generation)[source]
Record the tool-listing generation currently in effect.
- set_identity(server_id, identity)[source]
Bind a server’s record to an identity without changing anything else.
- launch_digest(server_id)[source]
Read the launch an operator last approved for a server.
- set_launch_digest(server_id, digest, *, identity=None)[source]
Record the launch an operator has just approved.
- compute_generation(entries)[source]
Digest a tool listing into a stable generation identifier.
The digest covers every field the operator would be consenting to: the name, the description, the argument schema and the behavioural annotations. Entries are sorted by name first, so a server that merely reorders its listing keeps the same generation and does not re-prompt, while any change to what a tool claims to be produces a new one.
- Parameters:
entries (Sequence[McpToolEntry]) – The tools to digest, in any order.
- Returns:
A hexadecimal digest, identical across processes and platforms.
- Return type:
- deny_all_launches(config, description, findings)[source]
Refuse every launch that would need an operator to answer.
This is the prompt a headless process runs with. A local server is never started without a human agreeing, so with nobody to ask, the answer is no.
- Parameters:
config (McpServerConfig) – The server that would be launched.
description (str) – The rendered launch description.
findings (list[DangerousPattern]) – Patterns flagged in the command.
- Returns:
Always
False.- Return type:
- describe_launch(spec, env, sandbox=None)[source]
Render exactly what will be run, for the operator to read before agreeing.
Every argument appears in full: nothing is truncated, elided or reflowed, because an argument the operator cannot see is an argument they cannot refuse. Environment entries appear by name only – their values are resolved credentials and must never be displayed. Whether the program runs sandboxed, and what that does and does not stop, is stated before anything else.
- Parameters:
spec (StdioServerSpec) – The configured launch description.
env (Mapping[str, str]) – The fully resolved environment the child will receive.
sandbox (McpSandboxSpec | None) – The server’s sandbox settings, or
Nonefor none.
- Returns:
A plain-text description suitable for a monospace, read-only view.
- Return type:
- enabled_entries(config, catalog)[source]
Resolve which of a server’s tools may be advertised.
A disabled server contributes nothing at all, which is the state every server starts in. An enabled server contributes every tool except those the operator has individually switched off.
- Parameters:
config (McpServerConfig) – The server’s configuration.
catalog (McpToolCatalog) – The server’s current tool listing.
- Returns:
The tools to advertise, in server order.
- Return type:
tuple[McpToolEntry, …]
- estimate_tool_cost(function, counter=None)[source]
Price one tool definition against the context window.
- Parameters:
function (ToolFunction) – The tool function as it would be advertised.
counter (TokenCounter | None) – Token counter to use, defaulting to the shared encoding.
- Returns:
The estimated cost of advertising
function.- Return type:
- expand_uri_template(template, values)[source]
Fill in a URI template.
An expression RFC 6570 does not define is refused with the
ValueErrorits parser raises.
- async fetch_catalog(client, server_id, *, cache_mode='use', request_deadline=<class 'contextlib.nullcontext'>)[source]
Retrieve a server’s complete tool listing.
Pagination is followed to exhaustion, preserving the order the server returned tools in. The freshness hints are taken from the first page, which is the one a cached re-list would be served from.
The SDK’s client keeps its own response cache, which honours the server’s
ttlMsfor the first page.cache_mode="refresh"sends the request regardless and replaces what the cache held, which is what a change notification calls for: the server has just said the cached listing is wrong.- Parameters:
client (Client) – A connected MCP client.
server_id (str) – The server’s configured id.
cache_mode (CacheMode) – How the SDK’s response cache treats the first page:
"use"serves a fresh cached page,"refresh"always asks the server and stores the answer,"bypass"always asks and stores nothing.request_deadline (Callable[[], AbstractAsyncContextManager[object]]) – Builds the deadline each page request runs under. The SDK client carries no timeout of its own, so this is what bounds a server that never answers.
- Return type:
A page that overruns its deadline propagates the
TimeoutErrorthe deadline raises.- Returns:
The complete listing.
- Return type:
- Raises:
McpProtocolError – If the server repeats a cursor, exceeds
MAX_LIST_PAGES, or publishes a duplicate tool name.- Parameters:
- from_canonical_name(canonical)[source]
Split a canonical MCP name back into its server id and tool name.
Only the first dot separates the two halves, so a tool whose own name contains dots survives the round trip.
- Parameters:
canonical (str) – A canonical name produced by
to_canonical_name().- Returns:
The server id and the server’s own tool name.
- Return type:
- Raises:
McpConfigError – If the name does not carry the MCP namespace prefix or has no tool component.
- is_mcp_namespace(namespace)[source]
Report whether a tool namespace belongs to an MCP server.
- map_result(result)[source]
Convert a protocol tool result into Intellicrack’s multi-part result.
Parts keep the order the server sent them, and structured content becomes a final structured part. Every piece of server prose is stripped of control characters and fenced as untrusted data; a text part longer than
MAX_TEXT_PART_CHARSis truncated inside its fence. Structured content is cleaned string by string, and a text block that merely restates it is marked, so a dialect sends one representation rather than both.Images are checked: a payload that is not valid base64, or whose bytes are not the image type declared, is replaced by a note saying why. At most
MAX_IMAGES_PER_RESULTimages andMAX_IMAGE_BYTES_PER_RESULTdecoded bytes of them are kept; the rest are described. Binary parts are never truncated, because half a base64 payload is not a smaller payload, it is a corrupt one. Everything else is bounded together: onceMAX_RESULT_BYTESis reached the remaining parts are replaced by a note saying how many were dropped, so a server cannot flood the context window with one call.- Parameters:
result (CallToolResult) – The server’s result.
- Returns:
The mapped parts and whether the server reported the call as an error.
- Return type:
- map_tool_to_function(entry)[source]
Convert a catalog entry into the tool definition the model sees.
The entry’s advertised schema is carried on
ToolFunction.input_schema, which the schema layer treats as authoritative, soparametersis deliberately left empty rather than being a lossy second description of the same thing. It keeps the structure the server published and carries none of the server’s text unsanitized.The server’s own description is fenced here, once, so every place the description travels – the system prompt,
tools.searchresults and each provider’s tool definitions – carries it as marked, bounded, control-free data rather than as instruction.- Parameters:
entry (McpToolEntry) – The server’s tool.
- Returns:
The advertised function.
- Return type:
- async run_context_tool(connection, tool, arguments, *, on_progress=None)[source]
Carry out one call to a server’s resources or prompts.
- Parameters:
connection (McpConnection) – The server’s connection.
tool (ContextTool) – The function called.
on_progress (ProgressFn | None) – Receives the server’s progress on a read or a fetch.
- Returns:
What the model receives.
- Return type:
- sanitize_untrusted_text(text, *, limit=4096)[source]
Bound and fence a piece of text an external party supplied.
- scan_command_for_dangerous_patterns(command, args)[source]
Find everything about a proposed launch worth flagging to the operator.
The scan is advisory: it never blocks a launch on its own, it raises the operator’s attention before they answer. Findings cover privilege escalation, recursive deletion, fetch-and-execute pipelines, opaque encoded commands, and paths that reach into the home directory, credential stores, or system locations.
- Parameters:
- Returns:
Findings in command-line order, without duplicates.
- Return type:
- server_identity(config)[source]
Digest what makes a configured server the server the operator judged.
Trust, refusals, approved launches and remembered tool approvals are filed under a server id, but an id is only a name: removing a server and adding a different one under the same id must not hand the newcomer the old one’s standing, and neither may changing what the same entry is allowed to do. The identity therefore covers where the transport leads and everything that widens what the server can reach: for a local server the launch command, its arguments, working directory, environment file, the configured environment values and the sandbox; for a remote one the endpoint, its query, its configured headers and its OAuth client. A configured value can hold a credential only as an
${input:id}reference, so no secret enters the digest.- Parameters:
config (McpServerConfig) – The configured server.
- Returns:
A hexadecimal digest, stable across processes.
- Return type:
- source_label(canonical_name)[source]
Render where a canonical MCP tool came from, for the operator.
- template_variables(template)[source]
List the variables a template expects, in order, each once.
An expression RFC 6570 does not define is refused with the
ValueErrorits parser raises.
- to_canonical_name(server_id, tool_name)[source]
Build the canonical dotted name one server tool is known by.
- validate_against_schema(value, schema)[source]
Validate a decoded JSON value against a JSON Schema.
Local
$refpointers are expanded first, so a schema built from$defsvalidates as written. Schema patterns share aPATTERN_VALIDATION_BUDGET_Stime budget for the whole call.- Parameters:
- Returns:
Every violation found, empty when the value conforms.
- Return type:
- validate_structured_content(entry, content)[source]
Check a tool’s structured output against the schema it published.
A tool that declares no
outputSchemapromises nothing about its structured content, so nothing is checked.- Parameters:
entry (McpToolEntry) – The tool whose result is being checked.
content (Mapping[str, Any]) – The structured content the server returned.
- Raises:
McpProtocolError – If the content violates the declared schema.
- Return type:
None
Submodules
OAuth for Model Context Protocol servers reached over HTTP. |
|
The tool listing one Model Context Protocol server publishes. |
|
The client-side features one MCP connection offers its server. |
|
The SDK client, declaring exactly the client capabilities Intellicrack implements on each protocol generation. |
|
Declarative configuration for third-party Model Context Protocol servers. |
|
Live connections to configured Model Context Protocol servers. |
|
Operator consent for Model Context Protocol servers and their tools. |
|
What a server says has changed about its resources and prompts. |
|
Tools the model uses to reach a server's resources and prompts. |
|
Error hierarchy for the Model Context Protocol client. |
|
Keeps the operator's thinking time out of a server's request deadlines. |
|
What a server's tools cost, and which of them the operator has turned on. |
|
Progress a server reports on a request that is still running. |
|
Resources and prompts published by connected MCP servers. |
|
The folders an MCP server is told it may work in: the |
|
Windows confinement for a local Model Context Protocol server process. |
|
Keyring-backed resolution of |
|
Log messages MCP servers send, routed into Intellicrack's own logging. |
|
Presents connected MCP servers to Intellicrack as ordinary tools. |
|
Transport construction for Model Context Protocol connections. |
|
Making a server's argument schema safe to put in front of a model. |
|
Filling in a resource template's URI, as RFC 6570 defines it. |
|
JSON Schema validation for structured tool output. |