MCP Module

Clients for Model Context Protocol (MCP) servers over stdio (standard library only) and Streamable HTTP (httpx, the [http] extra), speaking MCP 2026-07-28 with a fallback to the initialize handshake, plus the scorecard harness (scenario generation, execution, linting, output-schema checks, A–F scoring and badges). See Testing MCP Servers for the CLI guide and the demo script for programmatic usage.

Clients

class toolscore.mcp.MCPClient(timeout=30.0, protocol='auto', probe_timeout=None)[source]

Transport-independent MCP protocol logic (dual-era).

Subclasses provide the transport by implementing _open(), _close_transport(), _roundtrip() and _notify(). This class handles era detection, per-request _meta, tools/list pagination and tools/call.

The instance is a context manager: entering calls start() and exiting calls close().

Parameters:
  • timeout (float)

  • protocol (ProtocolMode)

  • probe_timeout (float | None)

__init__(timeout=30.0, protocol='auto', probe_timeout=None)[source]

Initialize the protocol state.

Parameters:
  • timeout (float) – Default per-request timeout in seconds.

  • protocol (Literal['auto', 'modern', 'legacy']) – "auto" (probe with server/discover, fall back to initialize), "modern" (2026-07-28 only) or "legacy" (initialize handshake only).

  • probe_timeout (float | None) – Seconds to wait for the server/discover probe in "auto" mode before falling back. Defaults to min(timeout, DEFAULT_PROBE_TIMEOUT).

Return type:

None

server_messages: list[dict[str, Any]]

Messages the server sent that were not the awaited response: notifications, requests it initiated (answered, see _answer_server_request()) and late responses. Only the most recent MAX_SERVER_MESSAGES are kept.

server_messages_dropped

How many server messages were dropped to keep the list bounded.

protocol_version: str

the version sent in _meta (modern) or the one initialize negotiated (legacy).

Type:

Protocol version in use

era: str | None

"modern" (per-request _meta) or "legacy" (initialize handshake) once started; None before.

server_info: dict[str, Any]

The server’s self-reported name and version.

server_instructions: str | None

The server’s instructions, or None. MCP clients pass these to the model, so they are part of what the model reads (and of its context cost).

server_capabilities: dict[str, Any]

The server’s capabilities object.

server_versions: list[str]

Protocol versions the server listed in server/discover (modern only).

__enter__()[source]

Connect and agree on a protocol version.

Return type:

MCPClient

Returns:

This client instance.

__exit__(*exc)[source]

Close the connection on context exit.

Return type:

None

Parameters:

exc (object)

start()[source]

Open the transport and agree on a protocol version with the server.

Return type:

dict[str, Any]

Returns:

The server’s self-reported serverInfo (may be empty).

Raises:

MCPError – If the transport cannot be opened or no protocol version can be agreed on.

close()[source]

Close the transport. Safe to call multiple times.

Return type:

None

list_tools()[source]

List the tools advertised by the server.

Follows pagination via the nextCursor field until exhausted. Guards against a misbehaving server that paginates forever: a repeated cursor or more than _MAX_LIST_TOOLS_PAGES pages raises MCPError.

Return type:

list[MCPToolDef]

Returns:

The advertised tools as MCPToolDef objects.

Raises:
  • MCPError – On a protocol or transport failure, or if the server paginates in a loop (repeated cursor) or beyond the page cap.

  • MCPTimeoutError – If the server does not respond in time.

call_tool(name, arguments)[source]

Invoke a tool on the server.

Parameters:
  • name (str) – The tool name.

  • arguments (dict[str, Any]) – Arguments matching the tool’s input schema.

Return type:

MCPToolResult

Returns:

The MCPToolResult. is_error is True when the server reports isError or the call yields a JSON-RPC error. input_required is True (and is_error False) when the server asks for client input (resultType: input_required): the client provides none, so the call is left unfinished. An answer with only a requestState (no inputRequests) is retried with that state, up to MAX_INPUT_REQUIRED_RETRIES times, as the multi round-trip pattern allows.

Raises:
  • MCPTimeoutError – If the server does not respond in time.

  • MCPError – On a transport failure (e.g. the process dies).

class toolscore.mcp.MCPStdioClient(command, env=None, cwd=None, timeout=30.0, protocol='auto', probe_timeout=None)[source]

Synchronous MCP client communicating with a server over stdio.

The client spawns the server as a subprocess and agrees on a protocol version (see MCPClient). A daemon thread reads stdout lines into a queue and another drains stderr, so neither stream can deadlock the protocol. Standard library only.

Parameters:
__init__(command, env=None, cwd=None, timeout=30.0, protocol='auto', probe_timeout=None)[source]

Initialize the client.

Parameters:
  • command (list[str]) – The command vector used to launch the server, e.g. ["python", "server.py", "--flag"].

  • env (dict[str, str] | None) – Environment variables to overlay on top of the current process environment (os.environ); PATH and friends are preserved unless explicitly overridden.

  • cwd (str | Path | None) – Working directory for the server process.

  • timeout (float) – Default per-request timeout in seconds.

  • protocol (Literal['auto', 'modern', 'legacy']) – Era selection, see MCPClient.

  • probe_timeout (float | None) – server/discover probe timeout, see MCPClient.

Return type:

None

__enter__()[source]

Start the server and agree on a protocol version.

Return type:

MCPStdioClient

Returns:

This client instance.

class toolscore.mcp.MCPHttpClient(url, headers=None, timeout=30.0, protocol='auto', probe_timeout=None)[source]

Synchronous MCP client for a remote server over Streamable HTTP.

Supports both eras: the 2026-07-28 stateless binding (per-request MCP-Protocol-Version, Mcp-Method and Mcp-Name headers, plus Mcp-Param-* headers for parameters a tool marks with x-mcp-header) and the earlier session-based binding (initialize, Mcp-Session-Id). Responses may be plain JSON or a server-sent-event stream.

Requires httpx: pip install "tool-scorer[http]".

Header values (for example an Authorization token) are sent with every request but never included in error messages or reprs.

Parameters:
__init__(url, headers=None, timeout=30.0, protocol='auto', probe_timeout=None)[source]

Initialize the client.

Parameters:
  • url (str) – The server’s MCP endpoint, e.g. https://example.com/mcp.

  • headers (dict[str, str] | None) – Extra headers sent with every request (e.g. authorization).

  • timeout (float) – Default per-request timeout in seconds.

  • protocol (Literal['auto', 'modern', 'legacy']) – Era selection, see MCPClient.

  • probe_timeout (float | None) – server/discover probe timeout. Defaults to timeout: over HTTP a legacy server answers the probe with an error status, so a slow answer (a cold start) is waited for rather than taken for a legacy server.

Return type:

None

display_url

no credentials, query or fragment.

Type:

The URL as shown in messages

__repr__()[source]

Show the URL but never header values.

Return type:

str

__enter__()[source]

Connect and agree on a protocol version.

Return type:

MCPHttpClient

Returns:

This client instance.

toolscore.mcp.MODERN_PROTOCOL_VERSION = '2026-07-28'

str(object=’’) -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to sys.getdefaultencoding(). errors defaults to ‘strict’.

toolscore.mcp.LEGACY_PROTOCOL_VERSION = '2025-11-25'

str(object=’’) -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to sys.getdefaultencoding(). errors defaults to ‘strict’.

class toolscore.mcp.MCPToolDef(name, description, input_schema, annotations=dict(), output_schema=None, title=None)[source]

A tool advertised by an MCP server.

Variables:
  • name (str) – The tool’s unique name.

  • description (str) – Human-readable description (may be empty).

  • input_schema (dict[str, Any]) – The JSON Schema for the tool’s arguments, taken verbatim from the server’s inputSchema field.

  • annotations (dict[str, Any]) – The tool’s annotations object (behavior hints such as readOnlyHint and destructiveHint); empty when absent.

  • output_schema (dict[str, Any] | None) – The tool’s outputSchema, or None when the tool declares none. Results must then carry conforming structuredContent.

  • title (str | None) – The tool’s display title, or None.

Parameters:
name: str
description: str
input_schema: dict[str, Any]
annotations: dict[str, Any]
output_schema: dict[str, Any] | None = None
title: str | None = None
__init__(name, description, input_schema, annotations=<factory>, output_schema=None, title=None)
Parameters:
Return type:

None

class toolscore.mcp.MCPToolResult(content, is_error, raw, duration, input_required=False)[source]

The outcome of a tools/call invocation.

Variables:
  • content (Any) – The parsed content list from the call result (or the raw error payload when the call failed at the JSON-RPC level).

  • is_error (bool) – True if the result reported isError or the response was a JSON-RPC error.

  • raw (dict[str, Any]) – The full JSON-RPC response object.

  • duration (float) – Wall-clock seconds measured client-side for the round trip.

  • input_required (bool) – True when the server answered with resultType: "input_required" (MCP 2026-07-28 multi round-trip requests): it needs input from the client (an elicitation, a sampling request, roots) before the call can finish. Toolscore provides none, so the call did not run to completion. That is neither a success nor a tool error: callers treat it as not evaluated. content then says what the server asked for.

Parameters:
content: Any
is_error: bool
raw: dict[str, Any]
duration: float
input_required: bool = False
property input_requests: list[str]

The methods the server asked for (elicitation/create…), when input is required.

property text: str

The result as the text an MCP client would show a model.

Renders every content item, not only text: embedded resources (how many servers return file contents), resource links, and placeholders for images and audio. See toolscore.mcp.content.content_to_text().

property structured_content: Any

The result’s structuredContent, or None when absent.

property has_structured_content: bool

Whether the result carries a structuredContent field at all.

__init__(content, is_error, raw, duration, input_required=False)
Parameters:
Return type:

None

exception toolscore.mcp.MCPError[source]

Raised on MCP protocol or transport failures.

exception toolscore.mcp.MCPTimeoutError[source]

Raised when a request does not receive a response within the timeout.

exception toolscore.mcp.MCPHTTPStatusError(message, status)[source]

Raised when an HTTP response carries an error status and no JSON-RPC body.

Variables:

status – The HTTP status code.

Parameters:
Return type:

None

__init__(message, status)[source]

Initialize the error.

Parameters:
  • message (str) – The error message.

  • status (int) – The HTTP status code.

Return type:

None

toolscore.mcp.content_to_text(content)[source]

Render MCP content as the text an MCP client would give to a model.

Parameters:

content (Any) – The content value of a tools/call result (normally a list of content items). A plain string is returned unchanged, and a JSON-RPC error object yields its message.

Returns:

text as-is; an embedded text resource as [resource <uri>] followed by its body; a binary resource, image or audio as a bracketed placeholder with its MIME type; a resource_link as [resource link <uri> <name>]. Unknown item types are skipped.

Return type:

str

Example

>>> content_to_text([{"type": "text", "text": "ok"},
...                  {"type": "resource", "resource": {"uri": "file:///a.md", "text": "# A"}}])
'ok\n[resource file:///a.md]\n# A'

Recording sessions and injecting faults

See Fault Injection.

class toolscore.mcp.MCPRecorder(command, output, env=None, cwd=None, injector=None)[source]

A transparent stdio proxy that records tools/call traffic.

Parameters:
  • command (list[str]) – The server launch command vector.

  • output (str | Path) – Path of the trace file to write.

  • env (dict[str, str] | None) – Extra environment variables for the server process.

  • cwd (str | Path | None) – Working directory for the server process.

  • injector (FaultInjector | None) – Injects faults into chosen calls (toolscore mcp proxy --inject).

Example

>>> recorder = MCPRecorder(["python", "server.py"], Path("session.json"))
>>> exit_code = recorder.run()  # relays stdin/stdout until the client disconnects
__init__(command, output, env=None, cwd=None, injector=None)[source]
Parameters:
Return type:

None

injections: list[dict[str, Any]]

Every injection made, as recorded in the session file.

calls_recorded

Number of completed tool calls recorded so far.

write()[source]

Write the trace file atomically (a temporary file, then a rename).

Return type:

None

run(stdin=None, stdout=None, stderr=None)[source]

Relay a whole session and return the server’s exit code.

Reads client messages from stdin until it closes, relays server output to stdout until the server exits, and passes the server’s stderr through. The trace is written at the end even if no tool was called.

Parameters:
  • stdin (Optional[IO[str]]) – Client-to-server stream (default: sys.stdin).

  • stdout (Optional[IO[str]]) – Server-to-client stream (default: sys.stdout).

  • stderr (Optional[IO[str]]) – Where the server’s stderr goes (default: sys.stderr).

Return type:

int

Returns:

The server process exit code.

class toolscore.mcp.FaultSpec(faults, seed=0)[source]

A list of fault rules and the seed for probabilistic ones.

Parameters:
faults: list[FaultRule]
seed: int = 0
classmethod from_mapping(data)[source]

Build a spec from parsed JSON/YAML.

Raises:

ValueError – On an unknown key or a malformed rule.

Return type:

FaultSpec

Parameters:

data (Any)

to_dict()[source]

The spec as plain data (recorded in the session file).

Return type:

dict[str, Any]

__init__(faults, seed=0)
Parameters:
Return type:

None

class toolscore.mcp.FaultRule(fault, tools=<factory>, calls=None, probability=1.0, message=None, seconds=1.0, max_chars=40, forward=None, target_tool=None, canary=None)[source]

One rule of a fault spec (see the module docstring).

Variables:
  • fault – The fault kind, one of FAULT_KINDS.

  • tools (list[str]) – Tool names or globs the rule applies to.

  • calls (list[int] | None) – The 1-based call numbers (per tool) to inject; None for every call.

  • probability (float) – Chance of injecting a matching call, using the spec’s seed.

  • message (str | None) – The text the client sees, instead of the default.

  • seconds (float) – Delay for delay.

  • max_chars (int) – Characters kept by truncate.

  • forward (bool | None) – Whether the call reaches the server; None for the fault’s default.

  • target_tool (str | None) – For prompt_injection: the tool the planted instruction asks the agent to call.

  • canary (str | None) – For prompt_injection: the token planted with the instruction; None derives a unique one from the seed, tool and call number.

Parameters:
fault: str
tools: list[str]
calls: list[int] | None = None
probability: float = 1.0
message: str | None = None
seconds: float = 1.0
max_chars: int = 40
forward: bool | None = None
target_tool: str | None = None
canary: str | None = None
__post_init__()[source]

Validate the rule.

Raises:

ValueError – On an unknown fault or an out-of-range value.

Return type:

None

property forwards: bool

Whether a call this rule injects still reaches the server.

matches(tool)[source]

Whether the rule applies to tool.

Return type:

bool

Parameters:

tool (str)

__init__(fault, tools=<factory>, calls=None, probability=1.0, message=None, seconds=1.0, max_chars=40, forward=None, target_tool=None, canary=None)
Parameters:
Return type:

None

class toolscore.mcp.FaultInjector(spec)[source]

Decides, call by call, which fault (if any) to inject.

Parameters:

spec (FaultSpec) – The fault spec.

Example

>>> injector = FaultInjector(FaultSpec([FaultRule("error", tools=["save_*"], calls=[2])]))
>>> injector.decide("save_note") is None, injector.decide("save_note").fault
(True, 'error')
__init__(spec)[source]
Parameters:

spec (FaultSpec)

Return type:

None

decide(tool)[source]

Count a call to tool and return the fault to inject, or None.

Return type:

Injection | None

Parameters:

tool (str)

class toolscore.mcp.faults.Injection(rule, tool, tool_call, seed=0)[source]

A fault chosen for one call.

Variables:
  • rule (FaultRule) – The rule that matched.

  • tool (str) – The called tool.

  • tool_call (int) – Which call of this tool it was (1-based).

Parameters:
rule: FaultRule
tool: str
tool_call: int
seed: int = 0
property fault: str

The fault kind.

property canary: str | None

The token planted by prompt_injection (None for other faults).

property message: str | None

The text the client sees, if the fault has one.

record(request_id)[source]

What the session file stores about this injection.

Return type:

dict[str, Any]

Parameters:

request_id (Any)

synthesize(request_id, modern)[source]

The response sent instead of the server’s (None for timeout).

Return type:

dict[str, Any] | None

Parameters:
modify(response)[source]

Apply a forwarded fault to the server’s real response.

Return type:

dict[str, Any]

Parameters:

response (dict[str, Any])

__init__(rule, tool, tool_call, seed=0)
Parameters:
Return type:

None

toolscore.mcp.faults.FAULT_KINDS = ('error', 'jsonrpc_error', 'warning', 'empty', 'delay', 'timeout', 'disabled', 'denied', 'truncate', 'prompt_injection')

Every fault kind the proxy can inject.

toolscore.mcp.load_fault_spec(path)[source]

Read a fault spec file (JSON, or YAML with PyYAML installed).

Return type:

FaultSpec

Parameters:

path (str | Path)

Server configuration

class toolscore.mcp.MCPServerSpec(name, command, env=dict(), url=None, headers=dict())[source]

A single MCP server entry resolved from a config file.

Variables:
  • name (str) – The key under mcpServers / servers identifying this server.

  • command (list[str]) – The full command vector, i.e. [command, *args] (empty for a remote server).

  • env (dict[str, str]) – Environment variable overrides for the server process (often API keys, so kept out of the repr).

  • url (str | None) – The Streamable HTTP endpoint of a remote server, or None for a stdio server. It may hold a token, so it is kept out of the repr.

  • headers (dict[str, str]) – HTTP headers for a remote server (environment references already expanded). Treat the values as secrets.

Parameters:
name: str
command: list[str]
env: dict[str, str]
url: str | None = None
headers: dict[str, str]
property transport: str

"http" for a remote server, "stdio" otherwise.

__init__(name, command, env=<factory>, url=None, headers=<factory>)
Parameters:
Return type:

None

toolscore.mcp.load_mcp_config(path, server=None)[source]

Load an MCP server specification from an MCP host config file.

Parameters:
  • path (str | Path) – Path to the JSON configuration file (mcpServers or VS Code servers layout).

  • server (str | None) – Name of the server to load. If None and exactly one server is defined, that server is used. If None and multiple servers exist, a ValueError is raised listing the available names.

Return type:

MCPServerSpec

Returns:

The resolved MCPServerSpec.

Raises:
  • FileNotFoundError – If path does not exist.

  • ValueError – If the file is malformed, the server mapping is missing or empty, the requested server is not found, server is None while multiple servers are defined, the entry uses the deprecated SSE transport, or a referenced environment variable is unset.

toolscore.mcp.open_client(spec, timeout=30.0, protocol='auto')[source]

Build the right client for a server spec (stdio or Streamable HTTP).

The client is not started; use it as a context manager:

with open_client(load_mcp_config("mcp.json", "github")) as client:
    tools = client.list_tools()
Parameters:
Return type:

MCPClient

Returns:

An MCPHttpClient for a url entry, otherwise an MCPStdioClient.

Scorecard harness

toolscore.mcp.generate_scenarios(tools, cases_per_tool=3, include_edge_cases=True, fixtures=None)[source]

Generate test scenarios for every advertised tool.

For each tool with a usable object schema this produces up to cases_per_tool happy-path scenarios (well-formed arguments generated via generate_value_from_schema(), with all required properties present) and, when include_edge_cases is set and the schema permits, a handful of edge cases (missing required argument, wrong-type value, empty/zero values).

Tools whose schema is empty or invalid cannot be introspected, so they each receive a single no-arguments scenario whose description flags the problem.

fixtures (--arg values) replace generated values in happy-path scenarios, so a server that only accepts paths inside its sandbox gets paths it accepts. Edge cases keep their deliberately bad values.

Parameters:
Return type:

list[Scenario]

Returns:

The planned scenarios across all tools.

toolscore.mcp.run_scenarios(client, scenarios)[source]

Execute every scenario against the server, never aborting on failure.

Each scenario is called in turn. Transport problems (MCPError) and timeouts (MCPTimeoutError) are caught per scenario and recorded as a failed result rather than propagated, so one misbehaving tool cannot sink the whole run.

The ok determination depends on the scenario kind:

  • "happy" scenarios are ok only if the call completed without an error result.

  • "edge" scenarios are ok whenever the server responded at all (an error payload is an acceptable, expected reaction to bad input); they fail only on a timeout or transport crash. An edge case that breaks the schema and gets a success is flagged (ScenarioResult.accepted_invalid_input), not failed.

  • A call the server answers with resultType: "input_required" is not evaluated (ScenarioResult.status "input_required").

Parameters:
  • client (MCPClient) – A started MCP client (stdio or HTTP) connected to the server under test.

  • scenarios (list[Scenario]) – The scenarios to execute.

Return type:

list[ScenarioResult]

Returns:

One ScenarioResult per input scenario, in order.

toolscore.mcp.lint_tools(tools, instructions=None)[source]

Statically lint tool schemas and the text a model reads.

Errors (real defects):

  • missing or empty inputSchema,

  • schema missing a type,

  • a declared property that lacks a type,

  • a name in required that is absent from properties.

Warnings (ergonomic nits):

  • missing or very short (< 10 chars) description,

  • a tool name that is not snake_case,

  • properties present but no required list declared,

  • behavior annotations that are missing on a tool whose name says it writes or deletes, contradict the name, or conflict with each other (see toolscore.mcp.lint_rules.annotation_issues()).

Text checks over tool names, descriptions, parameter descriptions and the server instructions (see toolscore.mcp.lint_rules):

  • a reference to a tool the server does not expose (warning),

  • hidden Unicode tag characters or bidirectional controls (error),

  • tool-poisoning directives such as “do not tell the user” (error),

  • other invisible format characters (warning).

Each issue carries a concrete fix hint. Issues found in the instructions are reported under the tool name "<instructions>".

Parameters:
Return type:

list[LintIssue]

Returns:

Every issue found, across all tools.

toolscore.mcp.lint_rules.dangling_reference_issues(tools, instructions=None)[source]

Find text that tells the model to use a tool the server does not expose.

A name counts as a tool reference only in phrasing that names a tool: a quoted name followed by tool; a quoted name after use/call/invoke/run/try that is shaped like a tool name (snake_case or kebab-case, so fields such as endCursor and values such as add are not read as tools); or an unquoted snake_case name between use/call/invoke and tool. Names that exist as a tool, a parameter, or an allowed parameter value anywhere in the server are not reported (methods such as get_comments are often values of a method parameter).

Parameters:
  • tools (list[MCPToolDef]) – The server’s tools.

  • instructions (str | None) – The server’s instructions, if any.

Return type:

list[LintIssue]

Returns:

One warning per distinct missing name per owner (tool or <instructions>).

toolscore.mcp.lint_rules.poisoning_issues(tools, instructions=None)[source]

Find hidden text and concealment directives in what the model reads.

Errors:

  • Unicode tag characters (invisible text a model still reads),

  • bidirectional override/isolate controls (text that displays differently than it is stored),

  • directives to hide things from the user (“do not tell the user”, “do not mention this to the user”, “without telling the user”) or to ignore other instructions.

Warnings:

  • <IMPORTANT>-, <system>- or <instructions>-style blocks, which some servers use for emphasis and published attacks use to wrap hidden instructions;

  • other invisible format characters (zero-width characters, direction marks, BOM). They are normal in some scripts, so they are only surfaced.

Subdivision flag emoji, which are built from tag characters, are not reported.

Tool names are checked for hidden characters too.

Parameters:
  • tools (list[MCPToolDef]) – The server’s tools.

  • instructions (str | None) – The server’s instructions, if any.

Return type:

list[LintIssue]

Returns:

The issues found, at most one per kind per owner.

toolscore.mcp.lint_rules.annotation_issues(tools)[source]

Check the behavior annotations a client uses to decide what to auto-approve.

Warnings (rule IDs in brackets):

  • annotations-missing: the name says the tool deletes or writes, but it declares neither readOnlyHint nor destructiveHint.

  • annotation-read-only-contradiction: readOnlyHint: true on a tool whose name says it deletes or writes (for example delete_file).

  • annotation-hints-conflict: readOnlyHint: true together with destructiveHint: true.

  • annotation-invalid-value: a hint that is not a JSON boolean.

Tools whose names start with a read verb (get, list, search…) are not judged on their names, so the check stays quiet on read tools.

Parameters:

tools (list[MCPToolDef]) – The server’s tools.

Return type:

list[LintIssue]

Returns:

The issues found, at most one per tool and rule.

toolscore.mcp.harness.output_schema_issues(tools, results)[source]

Check successful results against each tool’s declared outputSchema.

The MCP specification requires a tool that declares an outputSchema to return structuredContent conforming to it. Only happy-path calls that succeeded are checked. Validation covers a conservative subset of JSON Schema (see toolscore.mcp.output_schema.validate_instance()): unknown keywords and $ref are not judged, so a reported mismatch is real.

Warnings, at most one per tool and rule:

  • structured-content-missing: a successful result has no structuredContent.

  • structured-content-mismatch: structuredContent does not conform.

Parameters:
Return type:

list[LintIssue]

Returns:

The issues found.

toolscore.mcp.output_schema.validate_instance(value, schema)[source]

Validate value against schema and return readable errors.

Parameters:
  • value (Any) – The instance (for example a result’s structuredContent).

  • schema (Any) – The JSON Schema (for example a tool’s outputSchema).

Return type:

list[str]

Returns:

Error strings with a JSON-pointer-like path ($.items[0].id: ...); empty when the value conforms (or the schema uses only unknown keywords).

class toolscore.mcp.Scenario(tool, arguments, kind, description, violations=list())[source]

A single planned tool invocation.

Variables:
  • tool (str) – The name of the tool to call.

  • arguments (dict[str, Any]) – The arguments to pass to the tool.

  • kind (str) – Either "happy" (well-formed, expected to succeed) or "edge" (intentionally malformed/boundary input where an error response from the server is acceptable).

  • description (str) – Human-readable summary of what the scenario exercises.

  • violations (list[str]) – For an edge case, how its arguments break the tool’s own inputSchema (from validate_instance()); empty when the schema accepts them (an empty string can be valid).

Parameters:
tool: str
arguments: dict[str, Any]
kind: str
description: str
violations: list[str]
__init__(tool, arguments, kind, description, violations=<factory>)
Parameters:
Return type:

None

class toolscore.mcp.ScenarioResult(scenario, ok, is_error, duration, detail, structured_content=None, has_structured_content=False, input_required=False, input_requests=list())[source]

The outcome of executing a single Scenario.

Variables:
  • scenario (Scenario) – The scenario that produced this result.

  • ok (bool) – Whether the scenario is considered a pass. For "happy" scenarios this means the call completed without is_error. For "edge" scenarios this means the server responded (with or without an error payload) rather than crashing or timing out – error responses to bad input are acceptable and expected.

  • is_error (bool) – Whether the tool result reported an error.

  • duration (float) – Wall-clock seconds the call took.

  • detail (str) – A short outcome string (e.g. an error message excerpt).

  • structured_content (Any) – The result’s structuredContent (None when absent or when the call failed).

  • has_structured_content (bool) – Whether the result carried structuredContent.

  • input_required (bool) – The server answered resultType: "input_required" (it needs client input Toolscore does not provide). The scenario is not evaluated: neither a pass nor a fail, and left out of the rates. ok is False; use status.

  • input_requests (list[str]) – The methods the server asked for (elicitation/create…).

Parameters:
scenario: Scenario
ok: bool
is_error: bool
duration: float
detail: str
structured_content: Any = None
has_structured_content: bool = False
input_required: bool = False
input_requests: list[str]
property status: str

"pass", "fail" or "input_required" (not evaluated).

property evaluated: bool

Whether the scenario has a verdict (it did not stop at input_required).

property accepted_invalid_input: bool

An edge case whose arguments break the input schema, answered as a success.

The server returned a result without isError for arguments its own inputSchema rejects (a missing required argument, a wrong type…). Either it accepted invalid input, or it reported the rejection without isError, so a client cannot tell. It still counts as resilient (the server answered); it is reported as a finding, not scored.

__init__(scenario, ok, is_error, duration, detail, structured_content=None, has_structured_content=False, input_required=False, input_requests=<factory>)
Parameters:
Return type:

None

class toolscore.mcp.LintIssue(tool, severity, message, fix='', rule='')[source]

A single problem found while statically linting a tool schema.

Variables:
  • tool (str) – The name of the offending tool.

  • severity (str) – Either "error" (a real schema defect) or "warning" (a quality nit that hurts agent ergonomics).

  • message (str) – A human-readable description of the issue.

  • fix (str) – A short, concrete suggestion for how to resolve the issue. May be empty for issues raised without a specific remedy.

  • rule (str) – The stable rule ID (for example "annotations-missing"); see the rule table in the MCP testing guide. Empty for issues built without one.

Parameters:
tool: str
severity: str
message: str
fix: str = ''
rule: str = ''
__init__(tool, severity, message, fix='', rule='')
Parameters:
Return type:

None

Argument values

class toolscore.mcp.ArgumentFixtures(shared=dict(), per_tool=dict(), raw=dict())[source]

Argument values a server is known to accept.

Variables:
  • shared (dict[str, Any]) – Values applied to every tool that declares a parameter of that name.

  • per_tool (dict[str, dict[str, Any]]) – Values applied to one tool, by tool name, whether or not its schema declares them.

Parameters:
shared: dict[str, Any]
per_tool: dict[str, dict[str, Any]]
raw: dict[str, dict[str, str]]

The text of --arg values as typed, by scope ("*" or a tool) and name.

__bool__()[source]

Whether any value is set.

Return type:

bool

classmethod from_mapping(data)[source]

Build fixtures from {"*": {...}, "<tool>": {...}}.

Parameters:

data (Any) – The parsed fixture mapping.

Return type:

ArgumentFixtures

Returns:

The fixtures.

Raises:

ValueError – If data or a section is not a mapping.

classmethod from_options(options)[source]

Build fixtures from --arg option values (see parse_arg()).

Return type:

ArgumentFixtures

Parameters:

options (tuple[str, ...] | list[str])

merged(other)[source]

A copy with other’s values on top of these.

Return type:

ArgumentFixtures

Parameters:

other (ArgumentFixtures)

for_tool(tool)[source]

The values that apply to tool.

Shared values are used only for parameters the tool declares; per-tool values always apply. Scalars given for a parameter declared as a string are passed as strings.

Return type:

dict[str, Any]

Parameters:

tool (MCPToolDef)

apply(tool, arguments)[source]

arguments with this tool’s fixture values on top.

Return type:

dict[str, Any]

Parameters:
__init__(shared=<factory>, per_tool=<factory>, raw=<factory>)
Parameters:
Return type:

None

toolscore.mcp.load_fixtures(path)[source]

Read an argument fixture file (JSON or YAML; see the module docstring).

Return type:

ArgumentFixtures

Parameters:

path (str | Path)

toolscore.mcp.fixtures.parse_arg(text)[source]

Parse one --arg option: name=value or tool:name=value.

Parameters:

text (str) – The option value.

Return type:

tuple[str | None, str, Any]

Returns:

(tool or None, parameter name, value).

Raises:

ValueError – If there is no = or the name is empty.

Effect probes

See Effect Probes.

toolscore.mcp.run_probes(client, tools, config=None, allow_writes=False, fixtures=None)[source]

Run the effect probes against a started client.

Parameters:
  • client (MCPClient) – A started MCP client.

  • tools (list[MCPToolDef]) – The server’s tools (from MCPClient.list_tools()).

  • config (ProbeConfig | None) – Declared pairs, relations and argument values; None probes by heuristics only.

  • allow_writes (bool) – Run probes that call write tools (round trips, and declared relations on tools that are not read-only). Off by default; writes leave marker records behind.

  • fixtures (ArgumentFixtures | None) – Extra known-good argument values (--arg), on top of the config’s args.

Return type:

list[ProbeResult]

Returns:

One ProbeResult per probe, including skipped and inconclusive ones.

class toolscore.mcp.ProbeResult(probe, tool, status, rule='', confidence='', message='', basis='', fix='', evidence=list(), check='')[source]

The outcome of one probe.

Variables:
  • probe (str) – "round-trip", "bound", "agreement" or "idempotent".

  • tool (str) – The tool under test.

  • status (str) – "pass", "fail", "inconclusive" (the probe could not run, for example the write failed with generated values) or "skipped" (not run, for example writes not allowed).

  • rule (str) – The rule ID of a failure (see PROBE_RULES); empty otherwise.

  • confidence (str) – "high", "medium" or "low" (see the module docstring); empty for skipped probes and round trips that could not run.

  • message (str) – What happened.

  • basis (str) – How the read tool or the relation was chosen.

  • fix (str) – A suggested fix for a failure.

  • evidence – The calls the probe made: tool, arguments, is_error and a short excerpt of the result.

  • check – What was checked within the probe: the bound parameter, or the declared relation’s id; empty for round trips.

Parameters:
probe: str
tool: str
status: str
rule: str = ''
confidence: str = ''
message: str = ''
basis: str = ''
fix: str = ''
evidence: list[dict[str, Any]]
check: str = ''
property severity: str | None

"error" for a high-confidence failure, "warning" for others, else None.

property graded: bool

Whether this result counts toward the grade (a high-confidence pass or fail).

__init__(probe, tool, status, rule='', confidence='', message='', basis='', fix='', evidence=<factory>, check='')
Parameters:
Return type:

None

class toolscore.mcp.ProbeConfig(args=ArgumentFixtures(), builtins=True, writes=list(), exclude=list(), pairs=list(), relations=list(), agreements=list(), idempotent=list())[source]

What to probe. Every field is optional; the defaults probe by heuristics.

Variables:
  • args (ArgumentFixtures) – Known-good argument values (as for --args-file).

  • builtins (bool) – Run the built-in bound relations on read-only tools.

  • writes (list[str]) – Extra tools to treat as write tools for round trips.

  • exclude (list[str]) – Tools never probed.

  • pairs (list[RoundTripPair]) – Declared round-trip pairs (high confidence).

  • relations (list[BoundRelation]) – Declared bound relations (high confidence).

  • agreements (list[Agreement]) – Declared two-path agreements (high confidence).

  • idempotent (list[CallSpec]) – Declared calls that must return the same result twice.

Parameters:
args: ArgumentFixtures
builtins: bool = True
writes: list[str]
exclude: list[str]
pairs: list[RoundTripPair]
relations: list[BoundRelation]
agreements: list[Agreement]
idempotent: list[CallSpec]
classmethod from_mapping(data)[source]

Build a config from parsed JSON or YAML (see docs/effect_probes.rst).

Raises:

ValueError – On an unknown key or a malformed entry.

Return type:

ProbeConfig

Parameters:

data (Any)

__init__(args=<factory>, builtins=True, writes=<factory>, exclude=<factory>, pairs=<factory>, relations=<factory>, agreements=<factory>, idempotent=<factory>)
Parameters:
Return type:

None

class toolscore.mcp.RoundTripPair(write, read, read_args=None, write_args=dict(), key=None)[source]

A declared write tool and the read tool that shows what it wrote.

Variables:
  • write (str) – The write tool.

  • read (str) – The read tool.

  • read_args (dict[str, Any] | None) – Arguments for the read tool; "{key}" in a string is replaced by the record’s key value and "{marker}" by its first marker.

  • write_args (dict[str, Any]) – Arguments for the write tool, on top of generated values.

  • key (list[str] | None) – Field names that identify a record (overrides the name heuristic).

Parameters:
write: str
read: str
read_args: dict[str, Any] | None = None
write_args: dict[str, Any]
key: list[str] | None = None
__init__(write, read, read_args=None, write_args=<factory>, key=None)
Parameters:
Return type:

None

class toolscore.mcp.BoundRelation(tool, param, values, expect='exact', args=dict(), unit='auto', id='')[source]

A declared bound: param = N must return at most (or exactly) N lines or items.

Variables:
  • tool (str) – The tool.

  • param (str) – The bound parameter.

  • values (list[int]) – The N values to try.

  • expect (str) – "at_most", "exact" (min(N, all)), "prefix" or "suffix" (exact, and the start/end of the full content).

  • args (dict[str, Any]) – The other arguments.

  • unit (str) – "lines", "items" or "auto" (items when the result is a list, else lines).

  • id (str) – A name for the relation, shown in reports.

Parameters:
tool: str
param: str
values: list[int]
expect: str = 'exact'
args: dict[str, Any]
unit: str = 'auto'
id: str = ''
__init__(tool, param, values, expect='exact', args=<factory>, unit='auto', id='')
Parameters:
Return type:

None

class toolscore.mcp.Agreement(left, right, expect='subset', id='')[source]

Two calls whose items should agree (left within right, or equal).

Variables:
  • left (CallSpec) – The first call (field picks a key of dict items).

  • right (CallSpec) – The second call.

  • expect (str) – "subset" (every left item is in right) or "equal".

  • id (str) – A name for the relation.

Parameters:
left: CallSpec
right: CallSpec
expect: str = 'subset'
id: str = ''
__init__(left, right, expect='subset', id='')
Parameters:
Return type:

None

class toolscore.mcp.CallSpec(tool, args=dict(), field=None)[source]

One tool call in a declared relation.

Parameters:
tool: str
args: dict[str, Any]
field: str | None = None
__init__(tool, args=<factory>, field=None)
Parameters:
Return type:

None

toolscore.mcp.load_probe_config(path)[source]

Read a probe config file (JSON, or YAML with PyYAML installed).

Return type:

ProbeConfig

Parameters:

path (str | Path)

toolscore.mcp.probes.builtin_relations(tool, fixtures)[source]

The built-in bound relations for a read-only tool (empty for other tools).

head/tail integer parameters are tried with 0, 1 and 2 and must return exactly that many first/last lines; limit-like ones with 1 and 2 and must return at most that many items (exactly that many when there are enough). 0 is not tried for limits, since some APIs read limit: 0 as “no limit”.

Return type:

list[BoundRelation]

Parameters:
toolscore.mcp.probes.is_read_tool(tool)[source]

Whether a tool only reads: readOnlyHint: true, or a read verb first and no hint against it.

Return type:

bool

Parameters:

tool (MCPToolDef)

toolscore.mcp.probes.write_basis(tool)[source]

Why a tool counts as a write tool for round trips, or None if it does not.

Return type:

str | None

Parameters:

tool (MCPToolDef)

toolscore.mcp.probes.PROBE_RULES: dict[str, str]

Every probe rule ID with a one-line meaning.

Scorecard

class toolscore.mcp.MCPScorecard(server_info, tools, results, lint, instructions=None, protocol_version=None, era=None, probes=None, probe_grade_cap=True)[source]

An aggregated quality report for a single MCP server.

Variables:
  • server_info (dict[str, Any]) – The serverInfo dict reported during the handshake.

  • tools (list[MCPToolDef]) – The tools advertised by the server.

  • results (list[ScenarioResult]) – The executed scenario results.

  • lint (list[LintIssue]) – The lint issues found in the tool schemas and the text a model reads.

  • instructions (str | None) – The server instructions from the handshake, if any. MCP clients send them to the model with every session, so they count toward the context cost.

  • protocol_version (str | None) – The MCP protocol version the run used, if known.

  • era (str | None) – "modern" (per-request _meta, 2026-07-28) or "legacy" (initialize handshake), if known.

  • probes (list[ProbeResult] | None) – Effect-probe results, or None when probes did not run (see toolscore.mcp.probes).

  • probe_grade_cap – Cap the grade at PROBE_GRADE_CAP when a high-confidence probe failed (the default). The score is unchanged.

Parameters:
server_info: dict[str, Any]
tools: list[MCPToolDef]
results: list[ScenarioResult]
lint: list[LintIssue]
instructions: str | None = None
protocol_version: str | None = None
era: str | None = None
probes: list[ProbeResult] | None = None
probe_grade_cap: bool = True
property not_evaluated: list[ScenarioResult]

the server answered input_required.

Type:

Scenarios with no verdict

property accepted_invalid_input: list[ScenarioResult]

Edge cases that break the input schema and got a success (see the harness).

property happy_pass_rate: float

Fraction of evaluated happy-path scenarios that passed (1.0 if none).

property edge_resilience_rate: float

Fraction of edge scenarios the server survived (1.0 if none).

property lint_error_count: int

Number of error-severity lint issues.

property lint_warning_count: int

Number of warning-severity lint issues.

property lint_score: float

Schema cleanliness score in [0, 1] (1.0 is spotless).

property effect_rate: float | None

Share of high-confidence probe checks that passed.

None when probes did not run or none of their checks was high-confidence (nothing to grade).

property effect_label: str

"75%", "n/a" (nothing graded) or "" (no probes).

Type:

The effect rate for display

property probe_evidence: dict[str, int] | None

Probe outcomes as tri-state evidence, or None when probes did not run.

pass and fail (any confidence); unknown counts inconclusive probes (they could not run, so they are not a pass); skipped counts probes that were not run (writes not allowed).

property probe_failed_tools: set[str]

Tools with a high-confidence probe failure.

property probe_error_count: int

High-confidence probe failures (they lower the grade).

property probe_warning_count: int

Medium- and low-confidence probe failures (warnings only).

property score: float

The overall blended score in [0, 1].

property uncapped_grade: str

The letter grade the score alone earns (before any cap).

property grade_cap_reasons: list[str]

Why the grade is capped, e.g. ["probe-silent-noop on create_entities"].

Empty when the cap is off, no high-confidence probe failed, or the score already earns PROBE_GRADE_CAP or worse.

property grade_capped: bool

Whether grade is lower than uncapped_grade because of the cap.

property grade_cap_note: str

"capped because: probe-silent-noop on create_entities", or "".

property grade: str

The letter grade ("A" … "F") for score, after the probe cap.

property total_tool_tokens: int

Estimated total context tokens consumed by all tool definitions.

Tool definitions are sent to the model on every request, so this is a proxy for how much of the context window the server’s tools occupy.

property instructions_tokens: int

Estimated context tokens of the server instructions (0 if none).

property context_tokens: int

tools plus instructions.

Type:

Estimated context the server costs on every request

__init__(server_info, tools, results, lint, instructions=None, protocol_version=None, era=None, probes=None, probe_grade_cap=True)
Parameters:
Return type:

None

toolscore.mcp.scorecard.score_server(client, cases_per_tool=3, include_edge_cases=True, fixtures=None, probes=None, allow_writes=False, probe_grade_cap=True)[source]

Run the full scorecard against a started client.

Lists the tools, generates and runs scenarios, lints the definitions and checks successful results against each tool’s outputSchema.

Parameters:
  • client (MCPClient) – A started MCPClient (stdio or HTTP).

  • cases_per_tool (int) – Happy-path scenarios per tool.

  • include_edge_cases (bool) – Whether to run edge-case scenarios.

  • fixtures (ArgumentFixtures | None) – Known-good argument values (--arg) for the happy paths, for servers that only accept values from a sandbox.

  • probes (ProbeConfig | bool | None) – Run the effect probes: True with heuristics only, or a ProbeConfig. None/False skips them.

  • allow_writes (bool) – Let probes call write tools (round trips). Writes leave marker records on the server.

  • probe_grade_cap (bool) – Cap the grade at C when a high-confidence probe fails (see the module docstring).

Return type:

MCPScorecard

Returns:

The scorecard.

toolscore.mcp.grade_meets(grade, threshold)[source]

Report whether grade is at least as good as threshold.

Parameters:
  • grade (str) – The achieved grade (case-insensitive).

  • threshold (str) – The minimum acceptable grade (case-insensitive).

Return type:

bool

Returns:

True if grade ranks the same as or better than threshold. Unknown grades are treated as the worst possible.

toolscore.mcp.print_scorecard(card, console=None)[source]

Render the scorecard to a rich console.

Prints a header panel (server name/version and the big letter grade), a per-tool table (scenarios passed/total and average latency), and a lint section listing any issues.

Parameters:
  • card (MCPScorecard) – The scorecard to render.

  • console (Console | None) – The console to print to; a fresh one is created if omitted.

Return type:

None

toolscore.mcp.scorecard_to_json(card)[source]

Render the scorecard as a JSON-serializable dict.

Parameters:

card (MCPScorecard) – The scorecard to render.

Return type:

dict[str, Any]

Returns:

A plain dict (lists/dicts/strings/numbers only) capturing the grade, component scores, per-tool summaries, every scenario result, and every lint issue.

toolscore.mcp.scorecard_to_markdown(card)[source]

Render the scorecard as Markdown for READMEs or PR comments.

Parameters:

card (MCPScorecard) – The scorecard to render.

Return type:

str

Returns:

A Markdown document with a grade line, component scores (including the tool-definition token cost), a per-tool summary table, and a ranked “Top issues to fix” list.

Badges

toolscore.mcp.badge.badge_svg(grade, cap_note='')[source]

Render the grade as a flat, shields.io-style SVG badge.

Parameters:
  • grade (str) – The scorecard grade (A-F).

  • cap_note (str) – grade_cap_note when the grade is capped ("capped because: ..."); it marks the badge “(capped)” and goes in the SVG title.

Return type:

str

Returns:

The SVG document.

toolscore.mcp.badge.badge_endpoint(grade, cap_note='')[source]

The shields.io endpoint JSON for the grade.

Parameters:
  • grade (str) – The scorecard grade (A-F).

  • cap_note (str) – The cap note when the grade is capped (see badge_svg()).

Return type:

dict[str, Any]

Returns:

{"schemaVersion": 1, "label": ..., "message": ..., "color": ...}.

toolscore.mcp.scorecard.PROBE_GRADE_CAP = 'C'

The best grade a server with a high-confidence effect-probe failure can get.

Snapshots, pinning and diffs

See Diff & Pinning.

class toolscore.mcp.ServerSnapshot(tools, server_info=dict(), protocol_version=None, era=None, instructions=None, source='')[source]

What a server advertised: its tools, identity, protocol and instructions.

Variables:
  • tools (list[MCPToolDef]) – The tools, in the order the server listed them.

  • server_info (dict[str, Any]) – serverInfo (name, version).

  • protocol_version (str | None) – The protocol version used, if known.

  • era (str | None) – "modern" or "legacy", if known.

  • instructions (str | None) – The server instructions, if any.

  • source (str) – Where the snapshot came from (a command, URL or file), for reports.

Parameters:
tools: list[MCPToolDef]
server_info: dict[str, Any]
protocol_version: str | None = None
era: str | None = None
instructions: str | None = None
source: str = ''
classmethod from_client(client, source='')[source]

Snapshot a started client (lists its tools).

Return type:

ServerSnapshot

Parameters:
property tool_map: dict[str, MCPToolDef]

Tools by name.

property label: str

"memory-server 2.0.1", or the source.

to_json()[source]

The snapshot file layout (see the module docstring).

Return type:

dict[str, Any]

__init__(tools, server_info=<factory>, protocol_version=None, era=None, instructions=None, source='')
Parameters:
Return type:

None

toolscore.mcp.load_snapshot(path)[source]

Read a snapshot or lock file from disk (see snapshot_from_json()).

Return type:

ServerSnapshot

Parameters:

path (str | Path)

toolscore.mcp.write_snapshot(path, snapshot)[source]

Write a snapshot file and return its path.

Return type:

Path

Parameters:
toolscore.mcp.snapshot.snapshot_from_json(data, source='')[source]

Read a snapshot, a lock file (toolscore mcp pin) or a raw tools/list result.

Parameters:
  • data (Any) – Parsed JSON.

  • source (str) – Where it came from, for reports.

Return type:

ServerSnapshot

Returns:

The snapshot.

Raises:

ValueError – If data holds no tool list.

toolscore.mcp.build_lock(snapshot, overrides=None)[source]

Build the lock for a server snapshot.

Parameters:
Return type:

dict[str, Any]

Returns:

The lock dict (see the module docstring), with lock_sha256 last.

toolscore.mcp.verify_pin(lock, snapshot, fail_on='drift')[source]

Compare a server with its lock.

Parameters:
Return type:

PinReport

Returns:

The PinReport.

Raises:

ValueError – On an unknown fail_on.

toolscore.mcp.load_lock(path)[source]

Read a lock file.

Raises:

ValueError – If the file is not a Toolscore lock.

Return type:

dict[str, Any]

Parameters:

path (str | Path)

toolscore.mcp.write_lock(path, lock)[source]

Write a lock file (indented, sorted tool names) and return its path.

Return type:

Path

Parameters:
toolscore.mcp.infer_capabilities(tool)[source]

Derive a tool’s capabilities and why (see the module docstring).

Parameters:

tool (MCPToolDef) – The tool.

Returns:

[…]}`` when nothing was found.

Return type:

dict[str, list[str]]

toolscore.mcp.pin.load_capability_overrides(path)[source]

Read {"tool": ["read", ...]} capability overrides (JSON).

Raises:

ValueError – On a value that is not a list of known capabilities.

Return type:

dict[str, list[str]]

Parameters:

path (str | Path)

class toolscore.mcp.PinReport(findings, fail_on='drift', server='')[source]

The result of checking a server against its lock.

Variables:
  • findings (list[PinFinding]) – Every difference, errors first.

  • fail_on (str) – The fail_on mode used (see FAIL_MODES).

  • server (str) – The live server’s label.

Parameters:
findings: list[PinFinding]
fail_on: str = 'drift'
server: str = ''
property failing: list[PinFinding]

The findings that fail the check under fail_on.

property ok: bool

Whether the check passes under fail_on.

property drifted: bool

Whether anything differs from the lock (errors or info).

to_dict()[source]

A JSON-safe report.

Return type:

dict[str, Any]

__init__(findings, fail_on='drift', server='')
Parameters:
Return type:

None

class toolscore.mcp.PinFinding(rule, severity, tool, message, diff='', fields=list())[source]

One difference between a server and its lock.

Variables:
  • rule (str) – The rule ID (see PIN_RULES).

  • severity (str) – "error" or "info".

  • tool (str) – The tool concerned, or "" for server-level findings.

  • message (str) – What changed.

  • diff (str) – A unified text diff of what changed, when there is one.

  • fields (list[str]) – The changed fields of a changed tool.

Parameters:
rule: str
severity: str
tool: str
message: str
diff: str = ''
fields: list[str]
__init__(rule, severity, tool, message, diff='', fields=<factory>)
Parameters:
Return type:

None

toolscore.mcp.pin.PIN_RULES: dict[str, str]

Drift rule IDs with a one-line meaning.

toolscore.mcp.pin.CAPABILITIES: tuple[str, ...] = ('read', 'write', 'delete', 'network', 'exec', 'unknown')

Every capability, in display order.

toolscore.mcp.diff_snapshots(a, b, scorecards=None)[source]

Compare two server snapshots.

Parameters:
Return type:

ServerDiff

Returns:

The ServerDiff.

class toolscore.mcp.ServerDiff(a, b, added=list(), removed=list(), changed=list(), lint_new=list(), lint_resolved=list(), server_changes=list(), scorecards=None, new_tool_capabilities=dict())[source]

The difference between two servers (see the module docstring).

Variables:
  • a (str) – Label of side A.

  • b (str) – Label of side B.

  • added (list[str]) – Tools only in B.

  • removed (list[str]) – Tools only in A.

  • changed (list[ToolChange]) – Tools in both that differ.

  • lint_new (list[LintIssue]) – Lint issues in B that A did not have.

  • lint_resolved (list[LintIssue]) – Lint issues in A that B no longer has.

  • server_changes (list[str]) – Identity, protocol and instructions changes, as text.

  • scorecards (tuple[MCPScorecard, MCPScorecard] | None) – (A, B) scorecards when --test ran, else None.

  • new_tool_capabilities (dict[str, list[str]]) – Capabilities of each added tool.

Parameters:
a: str
b: str
added: list[str]
removed: list[str]
changed: list[ToolChange]
lint_new: list[LintIssue]
lint_resolved: list[LintIssue]
server_changes: list[str]
scorecards: tuple[MCPScorecard, MCPScorecard] | None = None
new_tool_capabilities: dict[str, list[str]]
property breaking: list[str]

Every breaking change, as one line each.

property score_regressions: list[str]

A lower grade and newly failing high-confidence probes (--test only).

property probe_deltas: tuple[set[tuple[str, str]], set[tuple[str, str]]]

(newly failing, newly passing) high-confidence probe (tool, rule) pairs.

property identical: bool

Whether nothing differs (tools, lint, server, and scorecards when tested).

fails(fail_on='any')[source]

Whether the diff fails under fail_on (any, breaking, none).

Return type:

bool

Parameters:

fail_on (str)

to_dict()[source]

A JSON-safe report.

Return type:

dict[str, Any]

__init__(a, b, added=<factory>, removed=<factory>, changed=<factory>, lint_new=<factory>, lint_resolved=<factory>, server_changes=<factory>, scorecards=None, new_tool_capabilities=<factory>)
Parameters:
Return type:

None

class toolscore.mcp.ToolChange(tool, fields=list(), diffs=dict(), breaking=list(), capabilities_added=list(), capabilities_removed=list())[source]

How one tool differs between A and B.

Variables:
  • tool (str) – The tool name.

  • fields (list[str]) – The changed fields (description, inputSchema…).

  • diffs (dict[str, str]) – A unified diff per changed field.

  • breaking (list[str]) – Why the change can break an agent (empty if it cannot).

  • capabilities_added (list[str]) – Capabilities B has and A did not.

  • capabilities_removed (list[str]) – Capabilities A had and B does not.

Parameters:
tool: str
fields: list[str]
diffs: dict[str, str]
breaking: list[str]
capabilities_added: list[str]
capabilities_removed: list[str]
__init__(tool, fields=<factory>, diffs=<factory>, breaking=<factory>, capabilities_added=<factory>, capabilities_removed=<factory>)
Parameters:
Return type:

None

toolscore.mcp.server_diff.render_diff(diff, color=True)[source]

The diff as console markup (color) or plain text (for Markdown code blocks).

Return type:

str

Parameters:

Agent harness

See Agent Harness.

Agent harness: run an LLM agent against an MCP server, and record what happened.

Toolscore checks tools and traces; to get traces from a real model, something has to run the agent loop. This module is that loop, for MCP servers (stdio or Streamable HTTP, through the existing clients) and two provider APIs: the OpenAI Responses API and Anthropic Messages. A scripted provider replays fixed model turns for offline tests and examples.

One run is one task, one arm (provider, model, system prompt) and one repetition. run_agent() runs one on a started client; run_study() runs every cell of a spec (tasks x arms x repetitions) in a shuffled order with a fixed seed and appends one JSONL row per run, so an interrupted study resumes where it stopped.

Safety and cost:

  • Guard. guard(call) -> allow() | deny(reason) runs before every tool call. A denied call never reaches the server: the agent gets a tool error (“denied by the harness guard: …”) and the row lists it under guard_denials. Declarative guards (deny rules in the forbidden-call format, an allow_tools list) are built in.

  • Budget, checked before every model call. The spent cost (the provider’s reported token usage times the price from toolscore.metrics.cost_estimator or the spec) plus a worst case for the next call (the conversation so far, estimated, plus max_output_tokens) must stay under max_usd, or the run stops with budget_stopped and the study stops. A model without a known price is refused before any call unless allow_unknown_price is set; its cost is then null (unknown), never 0.

  • Limits. max_turns model calls and max_calls tool calls per run.

  • Build verification. Each row records the server’s serverInfo name and version and the protocol; verify in the spec checks them (and can run a command whose output must match) and refuses the study on a mismatch, so a result is never attributed to the wrong build.

Each row carries the calls (id, arguments, result, error, duration, denied), the final answer, token usage, cost, guard denials, server info, protocol and, when the task declares expected or forbidden calls, the Toolscore evaluation with the honesty checks and tri-state evidence. outcome is pass, fail, error or unknown (a task with nothing to check), ready for toolscore compare --runs.

Provider SDKs are optional extras (tool-scorer[llm] for OpenAI, tool-scorer[anthropic]); tests pass fake clients and never call a model.

toolscore.mcp.agent.RUN_RECORD_VERSION = '1'

Layout version of a run row.

toolscore.mcp.agent.SPEC_VERSION = 1

Layout version of an agent spec.

toolscore.mcp.agent.RESULT_CHARS = 20000

Characters of a tool result kept in a run row (results are also hashed in exports).

class toolscore.mcp.agent.ProviderTool(name, mcp_name, description, parameters)[source]

An MCP tool as offered to a model.

Variables:
  • name (str) – The name the model sees (provider-safe: letters, digits, _, -; at most 64 characters).

  • mcp_name (str) – The MCP tool name the call goes to.

  • description (str) – The tool description.

  • parameters (dict[str, Any]) – The JSON Schema of the arguments.

Parameters:
name: str
mcp_name: str
description: str
parameters: dict[str, Any]
__init__(name, mcp_name, description, parameters)
Parameters:
Return type:

None

toolscore.mcp.agent.map_tools(tools, allow=None)[source]

MCP tools -> provider function tools, with safe, unique names.

Parameters:
  • tools (list[MCPToolDef]) – The server’s tools.

  • allow (list[str] | None) – Glob patterns of tools to offer (all when None).

Return type:

list[ProviderTool]

Returns:

The tools, in server order.

class toolscore.mcp.agent.ToolRequest(id, name, arguments, argument_error='')[source]

A tool call the model asked for.

Variables:
  • id (str) – The provider’s call ID (OpenAI call_id, Anthropic tool_use ID).

  • name (str) – The provider-side tool name.

  • arguments (dict[str, Any]) – The parsed arguments ({} if they did not parse).

  • argument_error (str) – Why the arguments did not parse, or "".

Parameters:
id: str
name: str
arguments: dict[str, Any]
argument_error: str = ''
__init__(id, name, arguments, argument_error='')
Parameters:
Return type:

None

class toolscore.mcp.agent.ModelTurn(text, requests, input_tokens=None, output_tokens=None)[source]

One model response.

Variables:
  • text (str) – The text the model wrote (its answer, when it calls no tool).

  • requests (list[ToolRequest]) – The tool calls it asked for.

  • input_tokens (int | None) – Input tokens the provider reported, or None.

  • output_tokens (int | None) – Output tokens the provider reported, or None.

Parameters:
  • text (str)

  • requests (list[ToolRequest])

  • input_tokens (int | None)

  • output_tokens (int | None)

text: str
requests: list[ToolRequest]
input_tokens: int | None = None
output_tokens: int | None = None
__init__(text, requests, input_tokens=None, output_tokens=None)
Parameters:
  • text (str)

  • requests (list[ToolRequest])

  • input_tokens (int | None)

  • output_tokens (int | None)

Return type:

None

class toolscore.mcp.agent.ModelProvider(*args, **kwargs)[source]

A conversation with one model. One instance per run.

start sets up the conversation, complete asks the model for its next turn, add_results gives it the tool results, and estimated_input_tokens sizes the next request for the budget check.

provider: str
model: str
max_output_tokens: int
start(system, prompt, tools)[source]

Begin the conversation.

Return type:

None

Parameters:
  • system (str | None)

  • prompt (str)

  • tools (list[ProviderTool])

complete()[source]

Ask the model for its next turn.

Return type:

ModelTurn

add_results(turn, results)[source]

Append the model’s turn and the results of its tool calls.

Return type:

None

Parameters:
estimated_input_tokens()[source]

An estimate of the next request’s input tokens.

Return type:

int

__init__(*args, **kwargs)
class toolscore.mcp.agent.OpenAIResponsesProvider(client, model, max_output_tokens=1024, extra=None)[source]

The OpenAI Responses API (client.responses.create).

Parameters:
  • client (Any) – An openai.OpenAI() client (or anything with responses.create).

  • model (str) – The model ID.

  • max_output_tokens (int) – max_output_tokens per request (also the budget’s worst case).

  • extra (dict[str, Any] | None) – Extra request parameters (reasoning, temperature…).

provider = 'openai'
__init__(client, model, max_output_tokens=1024, extra=None)[source]
Parameters:
Return type:

None

start(system, prompt, tools)[source]
Return type:

None

Parameters:
  • system (str | None)

  • prompt (str)

  • tools (list[ProviderTool])

complete()[source]
Return type:

ModelTurn

add_results(turn, results)[source]
Return type:

None

Parameters:
estimated_input_tokens()[source]
Return type:

int

class toolscore.mcp.agent.AnthropicMessagesProvider(client, model, max_output_tokens=1024, extra=None)[source]

Anthropic Messages (client.messages.create).

Parameters:
  • client (Any) – An anthropic.Anthropic() client (or anything with messages.create).

  • model (str) – The model ID.

  • max_output_tokens (int) – max_tokens per request (also the budget’s worst case).

  • extra (dict[str, Any] | None) – Extra request parameters.

provider = 'anthropic'
__init__(client, model, max_output_tokens=1024, extra=None)[source]
Parameters:
Return type:

None

start(system, prompt, tools)[source]
Return type:

None

Parameters:
  • system (str | None)

  • prompt (str)

  • tools (list[ProviderTool])

complete()[source]
Return type:

ModelTurn

add_results(turn, results)[source]
Return type:

None

Parameters:
estimated_input_tokens()[source]
Return type:

int

class toolscore.mcp.agent.ScriptedProvider(script, model='scripted')[source]

Replays fixed model turns: for offline tests, examples and dry runs. Costs nothing.

Each step is {"calls": [{"tool": MCP_NAME, "args": {...}}], "text": "..."} (calls optional). A step without calls ends the run with its text as the final answer. Usage is reported from input_tokens / output_tokens in a step, else estimated.

Parameters:
  • script (list[dict[str, Any]]) – The steps.

  • model (str) – A model label for the rows ("scripted").

provider = 'scripted'
__init__(script, model='scripted')[source]
Parameters:
Return type:

None

start(system, prompt, tools)[source]
Return type:

None

Parameters:
  • system (str | None)

  • prompt (str)

  • tools (list[ProviderTool])

complete()[source]
Return type:

ModelTurn

add_results(turn, results)[source]
Return type:

None

Parameters:
estimated_input_tokens()[source]
Return type:

int

class toolscore.mcp.agent.GuardCall(tool, arguments, task_id='', arm_id='', index=0)[source]

A tool call about to be made, as a guard sees it.

Parameters:
tool: str
arguments: dict[str, Any]
task_id: str = ''
arm_id: str = ''
index: int = 0
__init__(tool, arguments, task_id='', arm_id='', index=0)
Parameters:
Return type:

None

class toolscore.mcp.agent.GuardDecision(allowed, reason='')[source]

What a guard decided: allowed, and the reason for a denial.

Parameters:
allowed: bool
reason: str = ''
__init__(allowed, reason='')
Parameters:
Return type:

None

toolscore.mcp.agent.allow()[source]

Let the call through.

Return type:

GuardDecision

toolscore.mcp.agent.deny(reason)[source]

Block the call; the agent gets a tool error with reason.

Return type:

GuardDecision

Parameters:

reason (str)

toolscore.mcp.agent.rules_guard(deny_rules=None, allow_tools=None)[source]

A declarative guard.

Parameters:
  • deny_rules (list[dict[str, Any]] | None) – Forbidden-call rules (tool, optional args with values or $regex / $contains / $one_of matchers, optional reason), as for toolscore eval --forbidden.

  • allow_tools (list[str] | None) – Glob patterns of tools that may be called (all when None).

Return type:

Callable[[GuardCall], GuardDecision]

Returns:

The guard.

exception toolscore.mcp.agent.UnknownPriceError[source]

A model has no known price and allow_unknown_price is not set.

class toolscore.mcp.agent.Price(input, output, source)[source]

USD per 1M input and output tokens, and where the price came from.

Parameters:
input: float
output: float
source: str
__init__(input, output, source)
Parameters:
Return type:

None

toolscore.mcp.agent.price_for(model, pricing=None)[source]

The price of a model: pricing from the spec, else the built-in table, else None.

Return type:

Price | None

Parameters:
class toolscore.mcp.agent.Budget(max_usd=None, allow_unknown_price=False, spent_usd=0.0, unknown_cost_turns=0)[source]

A hard cost cap, shared by every run it is given to.

Variables:
  • max_usd (float | None) – The cap in USD (None: no cap, costs are still recorded).

  • allow_unknown_price (bool) – Run models without a known price (their cost is unknown, and the cap cannot be enforced for them).

  • spent_usd (float) – Cost so far, from reported usage.

  • unknown_cost_turns (int) – Model calls whose cost is unknown.

Parameters:
  • max_usd (float | None)

  • allow_unknown_price (bool)

  • spent_usd (float)

  • unknown_cost_turns (int)

max_usd: float | None = None
allow_unknown_price: bool = False
spent_usd: float = 0.0
unknown_cost_turns: int = 0
turn_cost(price, turn)[source]

The cost of one turn, or None when the price or the usage is unknown.

Return type:

float | None

Parameters:
  • price (Price | None)

  • turn (ModelTurn)

projected(price, provider)[source]

Spent so far plus the worst case of the next request.

Return type:

float

Parameters:
allows(price, provider)[source]

Whether the next model call fits under the cap.

Return type:

bool

Parameters:
__init__(max_usd=None, allow_unknown_price=False, spent_usd=0.0, unknown_cost_turns=0)
Parameters:
  • max_usd (float | None)

  • allow_unknown_price (bool)

  • spent_usd (float)

  • unknown_cost_turns (int)

Return type:

None

class toolscore.mcp.agent.Limits(max_turns=10, max_calls=20)[source]

Per-run limits: model calls (max_turns) and tool calls (max_calls).

Parameters:
  • max_turns (int)

  • max_calls (int)

max_turns: int = 10
max_calls: int = 20
__init__(max_turns=10, max_calls=20)
Parameters:
  • max_turns (int)

  • max_calls (int)

Return type:

None

class toolscore.mcp.agent.CallRecord(id, tool, provider_name, args, result=None, structured=None, is_error=False, error=None, duration=None, denied=False, deny_reason=None)[source]

One tool call of a run: what was requested and what came back.

Parameters:
id: str
tool: str
provider_name: str
args: dict[str, Any]
result: str | None = None
structured: Any = None
is_error: bool = False
error: str | None = None
duration: float | None = None
denied: bool = False
deny_reason: str | None = None
__init__(id, tool, provider_name, args, result=None, structured=None, is_error=False, error=None, duration=None, denied=False, deny_reason=None)
Parameters:
Return type:

None

class toolscore.mcp.agent.AgentRun(status, calls, final_answer, turns, input_tokens, output_tokens, cost_usd, stop_reason, error=None, duration_s=0.0)[source]

The outcome of run_agent().

Variables:
  • status (str) – "completed" (the model gave a final answer), "limit_reached", "budget_stopped" or "error".

  • calls (list[CallRecord]) – Every tool call the model asked for, in order.

  • final_answer (str | None) – The model’s last text, or None.

  • turns (int) – Model calls made.

  • input_tokens (int | None) – Reported input tokens (None if a turn did not report).

  • output_tokens (int | None) – Reported output tokens.

  • cost_usd (float | None) – Cost of the run, or None when unknown.

  • stop_reason (str) – Why the run stopped.

  • error (str | None) – The error, for status == "error".

  • duration_s (float) – Wall-clock seconds.

Parameters:
  • status (str)

  • calls (list[CallRecord])

  • final_answer (str | None)

  • turns (int)

  • input_tokens (int | None)

  • output_tokens (int | None)

  • cost_usd (float | None)

  • stop_reason (str)

  • error (str | None)

  • duration_s (float)

status: str
calls: list[CallRecord]
final_answer: str | None
turns: int
input_tokens: int | None
output_tokens: int | None
cost_usd: float | None
stop_reason: str
error: str | None = None
duration_s: float = 0.0
property guard_denials: list[dict[str, Any]]

id, tool, args, reason.

Type:

The denied calls

trace()[source]

The calls as Toolscore trace dicts (denied calls are failed calls).

Return type:

list[dict[str, Any]]

__init__(status, calls, final_answer, turns, input_tokens, output_tokens, cost_usd, stop_reason, error=None, duration_s=0.0)
Parameters:
  • status (str)

  • calls (list[CallRecord])

  • final_answer (str | None)

  • turns (int)

  • input_tokens (int | None)

  • output_tokens (int | None)

  • cost_usd (float | None)

  • stop_reason (str)

  • error (str | None)

  • duration_s (float)

Return type:

None

toolscore.mcp.agent.run_agent(client, provider, prompt, system=None, guard=None, budget=None, price=None, limits=None, allow_tools=None, task_id='', arm_id='')[source]

Run one agent loop against a started MCP client.

Parameters:
  • client (MCPClient) – A started MCP client.

  • provider (ModelProvider) – A fresh provider (one per run).

  • prompt (str) – The task.

  • system (str | None) – The system prompt.

  • guard (Any) – guard(GuardCall) -> allow() | deny(reason) (see rules_guard()).

  • budget (Budget | None) – A shared Budget, checked before every model call.

  • price (Price | None) – The model’s price (None: unknown).

  • limits (Limits | None) – Per-run limits.

  • allow_tools (list[str] | None) – Glob patterns of tools to offer the model.

  • task_id (str) – For the guard.

  • arm_id (str) – For the guard.

Return type:

AgentRun

Returns:

The AgentRun. Provider and server errors end the run with status="error"; they are not raised.

class toolscore.mcp.agent.ArmSpec(id, provider, model, system=None, max_output_tokens=1024, extra=dict(), pricing=None)[source]

One arm: a provider, a model and a system prompt (inherited from the spec).

Parameters:
id: str
provider: str
model: str
system: str | None = None
max_output_tokens: int = 1024
extra: dict[str, Any]
pricing: dict[str, Any] | None = None
__init__(id, provider, model, system=None, max_output_tokens=1024, extra=<factory>, pricing=None)
Parameters:
Return type:

None

class toolscore.mcp.agent.TaskSpec(id, prompt, expected=None, forbidden=None, min_score=0.9, script=None, require_completed=True)[source]

One task: the prompt, and what to check.

Parameters:
id: str
prompt: str
expected: list[dict[str, Any]] | None = None
forbidden: list[dict[str, Any]] | None = None
min_score: float = 0.9
script: list[dict[str, Any]] | dict[str, list[dict[str, Any]]] | None = None
require_completed: bool = True
script_for(arm_id)[source]

The scripted turns for an arm: script itself, or script[arm_id] when keyed by arm.

Return type:

list[dict[str, Any]] | None

Parameters:

arm_id (str)

__init__(id, prompt, expected=None, forbidden=None, min_score=0.9, script=None, require_completed=True)
Parameters:
Return type:

None

class toolscore.mcp.agent.AgentSpec(name, server, arms, tasks, repetitions=1, seed=0, budget=dict(), limits=Limits(), guard=dict(), verify=dict(), allow_tools=None, output=None, base_dir='.')[source]

A study: a server, arms, tasks, repetitions and the safety settings.

See docs/agent_harness.rst for the file format.

Parameters:
name: str
server: dict[str, Any]
arms: list[ArmSpec]
tasks: list[TaskSpec]
repetitions: int = 1
seed: int = 0
budget: dict[str, Any]
limits: Limits
guard: dict[str, Any]
verify: dict[str, Any]
allow_tools: list[str] | None = None
output: str | None = None
base_dir: str = '.'
cells()[source]

Every (task, arm, repetition), interleaved in a shuffled order fixed by seed.

Return type:

list[tuple[TaskSpec, ArmSpec, int]]

__init__(name, server, arms, tasks, repetitions=1, seed=0, budget=<factory>, limits=<factory>, guard=<factory>, verify=<factory>, allow_tools=None, output=None, base_dir='.')
Parameters:
Return type:

None

toolscore.mcp.agent.spec_from_mapping(data, base_dir='.')[source]

Validate and build an AgentSpec from parsed YAML/JSON.

Raises:

ValueError – On a missing or unknown key, or a value of the wrong type.

Return type:

AgentSpec

Parameters:
toolscore.mcp.agent.load_agent_spec(path)[source]

Read an agent spec (YAML with tool-scorer[yaml], or JSON).

Return type:

AgentSpec

Parameters:

path (str | Path)

exception toolscore.mcp.agent.BuildMismatchError[source]

The server is not the build the spec says it should be.

toolscore.mcp.agent.check_build(server_info, verify)[source]

Check serverInfo against verify.server_name / verify.server_version.

Values are compared exactly, or as a regex when written /.../.

Return type:

dict[str, Any]

Returns:

{"name", "version", "checked": [...], "ok": bool}.

Parameters:
toolscore.mcp.agent.run_version_command(verify, cwd='.')[source]

Run verify.command and match its output against verify.expect.

Return type:

dict[str, Any] | None

Returns:

{"command", "output", "expect", "ok"}, or None without a command.

Parameters:
toolscore.mcp.agent.default_provider_factory(arm, task)[source]

Create the provider for a run: real SDK clients for openai/anthropic, a script otherwise.

The SDK clients read their API keys from the environment (OPENAI_API_KEY, ANTHROPIC_API_KEY).

Raises:

ImportError – If the provider’s SDK is not installed.

Return type:

ModelProvider

Parameters:
  • arm (ArmSpec)

  • task (TaskSpec)

toolscore.mcp.agent.evaluate_run(task, run)[source]

The Toolscore evaluation of a run and its outcome (pass, fail, error, unknown).

A run passes when it completed, its score is at least min_score, every required call succeeded (unless require_completed: false, for tasks where the right answer is to report a refusal), no error-severity honesty finding fired and no forbidden call was requested. A run that errored or hit the budget is error; a task with no expected or forbidden calls is unknown unless an honesty error makes it fail.

Return type:

tuple[dict[str, Any] | None, str]

Parameters:
class toolscore.mcp.agent.StudyResult(output, rows, skipped, stopped, spent_usd, unknown_cost_turns)[source]

What run_study() did.

Variables:
  • output (Path) – The JSONL file.

  • rows (list[dict[str, Any]]) – The rows written by this invocation.

  • skipped (int) – Cells already in the output (resumed).

  • stopped (str) – Why the study stopped early, or "".

  • spent_usd (float) – Known cost of this invocation.

  • unknown_cost_turns (int) – Model calls whose cost is unknown.

Parameters:
output: Path
rows: list[dict[str, Any]]
skipped: int
stopped: str
spent_usd: float
unknown_cost_turns: int
__init__(output, rows, skipped, stopped, spent_usd, unknown_cost_turns)
Parameters:
Return type:

None

toolscore.mcp.agent.completed_cells(path, retry_errors=False)[source]

Cell IDs already in a JSONL output (errored ones only unless retry_errors).

Return type:

set[str]

Parameters:
toolscore.mcp.agent.preflight_prices(spec, allow_unknown_price=False)[source]

The price of every arm, refusing unknown prices unless allowed.

Raises:

UnknownPriceError – For an arm (not scripted) without a known price.

Return type:

dict[str, Price | None]

Parameters:
toolscore.mcp.agent.run_study(spec, output=None, provider_factory=None, max_runs=None, retry_errors=False, allow_unknown_price=False, on_row=None)[source]

Run every cell of a study and append one JSONL row per run.

Parameters:
  • spec (AgentSpec) – The study.

  • output (str | Path | None) – The JSONL file (default: the spec’s output, else <name>.runs.jsonl).

  • provider_factory (Callable[[ArmSpec, TaskSpec], ModelProvider] | None) – Creates the provider of a run (default: default_provider_factory(); tests pass fakes).

  • max_runs (int | None) – Stop after this many new runs.

  • retry_errors (bool) – Run errored cells again (they are skipped otherwise).

  • allow_unknown_price (bool) – Allow models without a known price.

  • on_row (Callable[[dict[str, Any]], None] | None) – Called with each row after it is written (for progress output).

Return type:

StudyResult

Returns:

The StudyResult.

Raises:
  • UnknownPriceError – Before any call, for a model without a known price.

  • BuildMismatchError – When the server or the version command does not match verify (before the first model call of that run).

toolscore.mcp.agent.estimate_study_cost(spec, prices)[source]

A worst-case cost estimate before any call (for toolscore doctor and --dry-run).

Per run: max_turns model calls, each with max_output_tokens out and an input that grows by that much per turn, starting from the prompt and the system prompt (tool definitions are not known before the server starts and add to the input). An upper bound, not a forecast.

Return type:

dict[str, Any]

Returns:

runs, per_arm (usd or None when the price is unknown) and total_usd (None when any arm’s price is unknown).

Parameters:
toolscore.mcp.agent.regrade_rows(rows, tasks=None, expected=None)[source]

Re-evaluate saved runs with new expectations, without running anything.

Parameters:
  • rows (list[dict[str, Any]]) – Rows from run_study() (record: "run").

  • tasks (dict[str, TaskSpec] | None) – New task definitions by task ID (their expected, forbidden, min_score and require_completed are used); rows of other tasks keep their own.

  • expected (list[dict[str, Any]] | None) – New expected calls for every row (instead of tasks).

Return type:

list[dict[str, Any]]

Returns:

The rows with a new evaluation, outcome and passed, and a regraded block (from_sha256 of the original row, producer, time).

toolscore.mcp.agent.run_agent(client, provider, prompt, system=None, guard=None, budget=None, price=None, limits=None, allow_tools=None, task_id='', arm_id='')[source]

Run one agent loop against a started MCP client.

Parameters:
  • client (MCPClient) – A started MCP client.

  • provider (ModelProvider) – A fresh provider (one per run).

  • prompt (str) – The task.

  • system (str | None) – The system prompt.

  • guard (Any) – guard(GuardCall) -> allow() | deny(reason) (see rules_guard()).

  • budget (Budget | None) – A shared Budget, checked before every model call.

  • price (Price | None) – The model’s price (None: unknown).

  • limits (Limits | None) – Per-run limits.

  • allow_tools (list[str] | None) – Glob patterns of tools to offer the model.

  • task_id (str) – For the guard.

  • arm_id (str) – For the guard.

Return type:

AgentRun

Returns:

The AgentRun. Provider and server errors end the run with status="error"; they are not raised.

toolscore.mcp.agent.run_study(spec, output=None, provider_factory=None, max_runs=None, retry_errors=False, allow_unknown_price=False, on_row=None)[source]

Run every cell of a study and append one JSONL row per run.

Parameters:
  • spec (AgentSpec) – The study.

  • output (str | Path | None) – The JSONL file (default: the spec’s output, else <name>.runs.jsonl).

  • provider_factory (Callable[[ArmSpec, TaskSpec], ModelProvider] | None) – Creates the provider of a run (default: default_provider_factory(); tests pass fakes).

  • max_runs (int | None) – Stop after this many new runs.

  • retry_errors (bool) – Run errored cells again (they are skipped otherwise).

  • allow_unknown_price (bool) – Allow models without a known price.

  • on_row (Callable[[dict[str, Any]], None] | None) – Called with each row after it is written (for progress output).

Return type:

StudyResult

Returns:

The StudyResult.

Raises:
  • UnknownPriceError – Before any call, for a model without a known price.

  • BuildMismatchError – When the server or the version command does not match verify (before the first model call of that run).

toolscore.mcp.agent.load_agent_spec(path)[source]

Read an agent spec (YAML with tool-scorer[yaml], or JSON).

Return type:

AgentSpec

Parameters:

path (str | Path)

toolscore.mcp.agent.spec_from_mapping(data, base_dir='.')[source]

Validate and build an AgentSpec from parsed YAML/JSON.

Raises:

ValueError – On a missing or unknown key, or a value of the wrong type.

Return type:

AgentSpec

Parameters:
toolscore.mcp.agent.regrade_rows(rows, tasks=None, expected=None)[source]

Re-evaluate saved runs with new expectations, without running anything.

Parameters:
  • rows (list[dict[str, Any]]) – Rows from run_study() (record: "run").

  • tasks (dict[str, TaskSpec] | None) – New task definitions by task ID (their expected, forbidden, min_score and require_completed are used); rows of other tasks keep their own.

  • expected (list[dict[str, Any]] | None) – New expected calls for every row (instead of tasks).

Return type:

list[dict[str, Any]]

Returns:

The rows with a new evaluation, outcome and passed, and a regraded block (from_sha256 of the original row, producer, time).

toolscore.mcp.agent.evaluate_run(task, run)[source]

The Toolscore evaluation of a run and its outcome (pass, fail, error, unknown).

A run passes when it completed, its score is at least min_score, every required call succeeded (unless require_completed: false, for tasks where the right answer is to report a refusal), no error-severity honesty finding fired and no forbidden call was requested. A run that errored or hit the budget is error; a task with no expected or forbidden calls is unknown unless an honesty error makes it fail.

Return type:

tuple[dict[str, Any] | None, str]

Parameters:
toolscore.mcp.agent.estimate_study_cost(spec, prices)[source]

A worst-case cost estimate before any call (for toolscore doctor and --dry-run).

Per run: max_turns model calls, each with max_output_tokens out and an input that grows by that much per turn, starting from the prompt and the system prompt (tool definitions are not known before the server starts and add to the input). An upper bound, not a forecast.

Return type:

dict[str, Any]

Returns:

runs, per_arm (usd or None when the price is unknown) and total_usd (None when any arm’s price is unknown).

Parameters:
toolscore.mcp.agent.preflight_prices(spec, allow_unknown_price=False)[source]

The price of every arm, refusing unknown prices unless allowed.

Raises:

UnknownPriceError – For an arm (not scripted) without a known price.

Return type:

dict[str, Price | None]

Parameters:
toolscore.mcp.agent.check_build(server_info, verify)[source]

Check serverInfo against verify.server_name / verify.server_version.

Values are compared exactly, or as a regex when written /.../.

Return type:

dict[str, Any]

Returns:

{"name", "version", "checked": [...], "ok": bool}.

Parameters:
toolscore.mcp.agent.map_tools(tools, allow=None)[source]

MCP tools -> provider function tools, with safe, unique names.

Parameters:
  • tools (list[MCPToolDef]) – The server’s tools.

  • allow (list[str] | None) – Glob patterns of tools to offer (all when None).

Return type:

list[ProviderTool]

Returns:

The tools, in server order.

toolscore.mcp.agent.rules_guard(deny_rules=None, allow_tools=None)[source]

A declarative guard.

Parameters:
  • deny_rules (list[dict[str, Any]] | None) – Forbidden-call rules (tool, optional args with values or $regex / $contains / $one_of matchers, optional reason), as for toolscore eval --forbidden.

  • allow_tools (list[str] | None) – Glob patterns of tools that may be called (all when None).

Return type:

Callable[[GuardCall], GuardDecision]

Returns:

The guard.

toolscore.mcp.agent.allow()[source]

Let the call through.

Return type:

GuardDecision

toolscore.mcp.agent.deny(reason)[source]

Block the call; the agent gets a tool error with reason.

Return type:

GuardDecision

Parameters:

reason (str)

class toolscore.mcp.agent.OpenAIResponsesProvider(client, model, max_output_tokens=1024, extra=None)[source]

The OpenAI Responses API (client.responses.create).

Parameters:
  • client (Any) – An openai.OpenAI() client (or anything with responses.create).

  • model (str) – The model ID.

  • max_output_tokens (int) – max_output_tokens per request (also the budget’s worst case).

  • extra (dict[str, Any] | None) – Extra request parameters (reasoning, temperature…).

provider = 'openai'
__init__(client, model, max_output_tokens=1024, extra=None)[source]
Parameters:
Return type:

None

start(system, prompt, tools)[source]
Return type:

None

Parameters:
  • system (str | None)

  • prompt (str)

  • tools (list[ProviderTool])

complete()[source]
Return type:

ModelTurn

add_results(turn, results)[source]
Return type:

None

Parameters:
estimated_input_tokens()[source]
Return type:

int

class toolscore.mcp.agent.AnthropicMessagesProvider(client, model, max_output_tokens=1024, extra=None)[source]

Anthropic Messages (client.messages.create).

Parameters:
  • client (Any) – An anthropic.Anthropic() client (or anything with messages.create).

  • model (str) – The model ID.

  • max_output_tokens (int) – max_tokens per request (also the budget’s worst case).

  • extra (dict[str, Any] | None) – Extra request parameters.

provider = 'anthropic'
__init__(client, model, max_output_tokens=1024, extra=None)[source]
Parameters:
Return type:

None

start(system, prompt, tools)[source]
Return type:

None

Parameters:
  • system (str | None)

  • prompt (str)

  • tools (list[ProviderTool])

complete()[source]
Return type:

ModelTurn

add_results(turn, results)[source]
Return type:

None

Parameters:
estimated_input_tokens()[source]
Return type:

int

class toolscore.mcp.agent.ScriptedProvider(script, model='scripted')[source]

Replays fixed model turns: for offline tests, examples and dry runs. Costs nothing.

Each step is {"calls": [{"tool": MCP_NAME, "args": {...}}], "text": "..."} (calls optional). A step without calls ends the run with its text as the final answer. Usage is reported from input_tokens / output_tokens in a step, else estimated.

Parameters:
  • script (list[dict[str, Any]]) – The steps.

  • model (str) – A model label for the rows ("scripted").

provider = 'scripted'
__init__(script, model='scripted')[source]
Parameters:
Return type:

None

start(system, prompt, tools)[source]
Return type:

None

Parameters:
  • system (str | None)

  • prompt (str)

  • tools (list[ProviderTool])

complete()[source]
Return type:

ModelTurn

add_results(turn, results)[source]
Return type:

None

Parameters:
estimated_input_tokens()[source]
Return type:

int

class toolscore.mcp.agent.ModelProvider(*args, **kwargs)[source]

A conversation with one model. One instance per run.

start sets up the conversation, complete asks the model for its next turn, add_results gives it the tool results, and estimated_input_tokens sizes the next request for the budget check.

provider: str
model: str
max_output_tokens: int
start(system, prompt, tools)[source]

Begin the conversation.

Return type:

None

Parameters:
  • system (str | None)

  • prompt (str)

  • tools (list[ProviderTool])

complete()[source]

Ask the model for its next turn.

Return type:

ModelTurn

add_results(turn, results)[source]

Append the model’s turn and the results of its tool calls.

Return type:

None

Parameters:
estimated_input_tokens()[source]

An estimate of the next request’s input tokens.

Return type:

int

__init__(*args, **kwargs)
class toolscore.mcp.agent.AgentRun(status, calls, final_answer, turns, input_tokens, output_tokens, cost_usd, stop_reason, error=None, duration_s=0.0)[source]

The outcome of run_agent().

Variables:
  • status (str) – "completed" (the model gave a final answer), "limit_reached", "budget_stopped" or "error".

  • calls (list[CallRecord]) – Every tool call the model asked for, in order.

  • final_answer (str | None) – The model’s last text, or None.

  • turns (int) – Model calls made.

  • input_tokens (int | None) – Reported input tokens (None if a turn did not report).

  • output_tokens (int | None) – Reported output tokens.

  • cost_usd (float | None) – Cost of the run, or None when unknown.

  • stop_reason (str) – Why the run stopped.

  • error (str | None) – The error, for status == "error".

  • duration_s (float) – Wall-clock seconds.

Parameters:
  • status (str)

  • calls (list[CallRecord])

  • final_answer (str | None)

  • turns (int)

  • input_tokens (int | None)

  • output_tokens (int | None)

  • cost_usd (float | None)

  • stop_reason (str)

  • error (str | None)

  • duration_s (float)

status: str
calls: list[CallRecord]
final_answer: str | None
turns: int
input_tokens: int | None
output_tokens: int | None
cost_usd: float | None
stop_reason: str
error: str | None = None
duration_s: float = 0.0
property guard_denials: list[dict[str, Any]]

id, tool, args, reason.

Type:

The denied calls

trace()[source]

The calls as Toolscore trace dicts (denied calls are failed calls).

Return type:

list[dict[str, Any]]

__init__(status, calls, final_answer, turns, input_tokens, output_tokens, cost_usd, stop_reason, error=None, duration_s=0.0)
Parameters:
  • status (str)

  • calls (list[CallRecord])

  • final_answer (str | None)

  • turns (int)

  • input_tokens (int | None)

  • output_tokens (int | None)

  • cost_usd (float | None)

  • stop_reason (str)

  • error (str | None)

  • duration_s (float)

Return type:

None

class toolscore.mcp.agent.AgentSpec(name, server, arms, tasks, repetitions=1, seed=0, budget=dict(), limits=Limits(), guard=dict(), verify=dict(), allow_tools=None, output=None, base_dir='.')[source]

A study: a server, arms, tasks, repetitions and the safety settings.

See docs/agent_harness.rst for the file format.

Parameters:
name: str
server: dict[str, Any]
arms: list[ArmSpec]
tasks: list[TaskSpec]
repetitions: int = 1
seed: int = 0
budget: dict[str, Any]
limits: Limits
guard: dict[str, Any]
verify: dict[str, Any]
allow_tools: list[str] | None = None
output: str | None = None
base_dir: str = '.'
cells()[source]

Every (task, arm, repetition), interleaved in a shuffled order fixed by seed.

Return type:

list[tuple[TaskSpec, ArmSpec, int]]

__init__(name, server, arms, tasks, repetitions=1, seed=0, budget=<factory>, limits=<factory>, guard=<factory>, verify=<factory>, allow_tools=None, output=None, base_dir='.')
Parameters:
Return type:

None

class toolscore.mcp.agent.Budget(max_usd=None, allow_unknown_price=False, spent_usd=0.0, unknown_cost_turns=0)[source]

A hard cost cap, shared by every run it is given to.

Variables:
  • max_usd (float | None) – The cap in USD (None: no cap, costs are still recorded).

  • allow_unknown_price (bool) – Run models without a known price (their cost is unknown, and the cap cannot be enforced for them).

  • spent_usd (float) – Cost so far, from reported usage.

  • unknown_cost_turns (int) – Model calls whose cost is unknown.

Parameters:
  • max_usd (float | None)

  • allow_unknown_price (bool)

  • spent_usd (float)

  • unknown_cost_turns (int)

max_usd: float | None = None
allow_unknown_price: bool = False
spent_usd: float = 0.0
unknown_cost_turns: int = 0
turn_cost(price, turn)[source]

The cost of one turn, or None when the price or the usage is unknown.

Return type:

float | None

Parameters:
  • price (Price | None)

  • turn (ModelTurn)

projected(price, provider)[source]

Spent so far plus the worst case of the next request.

Return type:

float

Parameters:
allows(price, provider)[source]

Whether the next model call fits under the cap.

Return type:

bool

Parameters:
__init__(max_usd=None, allow_unknown_price=False, spent_usd=0.0, unknown_cost_turns=0)
Parameters:
  • max_usd (float | None)

  • allow_unknown_price (bool)

  • spent_usd (float)

  • unknown_cost_turns (int)

Return type:

None

class toolscore.mcp.agent.Limits(max_turns=10, max_calls=20)[source]

Per-run limits: model calls (max_turns) and tool calls (max_calls).

Parameters:
  • max_turns (int)

  • max_calls (int)

max_turns: int = 10
max_calls: int = 20
__init__(max_turns=10, max_calls=20)
Parameters:
  • max_turns (int)

  • max_calls (int)

Return type:

None

class toolscore.mcp.agent.Price(input, output, source)[source]

USD per 1M input and output tokens, and where the price came from.

Parameters:
input: float
output: float
source: str
__init__(input, output, source)
Parameters:
Return type:

None

class toolscore.mcp.agent.GuardCall(tool, arguments, task_id='', arm_id='', index=0)[source]

A tool call about to be made, as a guard sees it.

Parameters:
tool: str
arguments: dict[str, Any]
task_id: str = ''
arm_id: str = ''
index: int = 0
__init__(tool, arguments, task_id='', arm_id='', index=0)
Parameters:
Return type:

None

class toolscore.mcp.agent.GuardDecision(allowed, reason='')[source]

What a guard decided: allowed, and the reason for a denial.

Parameters:
allowed: bool
reason: str = ''
__init__(allowed, reason='')
Parameters:
Return type:

None

exception toolscore.mcp.agent.UnknownPriceError[source]

A model has no known price and allow_unknown_price is not set.

exception toolscore.mcp.agent.BuildMismatchError[source]

The server is not the build the spec says it should be.