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/listpagination andtools/call.The instance is a context manager: entering calls
start()and exiting callsclose().- __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 withserver/discover, fall back toinitialize),"modern"(2026-07-28 only) or"legacy"(initializehandshake only).probe_timeout (
float|None) – Seconds to wait for theserver/discoverprobe in"auto"mode before falling back. Defaults tomin(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 recentMAX_SERVER_MESSAGESare 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 oneinitializenegotiated (legacy).- Type:
Protocol version in use
- era: str | None
"modern"(per-request_meta) or"legacy"(initializehandshake) once started;Nonebefore.
- server_instructions: str | None
The server’s
instructions, orNone. MCP clients pass these to the model, so they are part of what the model reads (and of its context cost).
- __enter__()[source]
Connect and agree on a protocol version.
- Return type:
- Returns:
This client instance.
- list_tools()[source]
List the tools advertised by the server.
Follows pagination via the
nextCursorfield until exhausted. Guards against a misbehaving server that paginates forever: a repeated cursor or more than_MAX_LIST_TOOLS_PAGESpages raisesMCPError.- Return type:
- Returns:
The advertised tools as
MCPToolDefobjects.- 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:
- Return type:
- Returns:
The
MCPToolResult.is_errorisTruewhen the server reportsisErroror the call yields a JSON-RPC error.input_requiredisTrue(andis_errorFalse) when the server asks for client input (resultType: input_required): the client provides none, so the call is left unfinished. An answer with only arequestState(noinputRequests) is retried with that state, up toMAX_INPUT_REQUIRED_RETRIEStimes, 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);PATHand 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, seeMCPClient.probe_timeout (
float|None) –server/discoverprobe timeout, seeMCPClient.
- Return type:
None
- 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-MethodandMcp-Nameheaders, plusMcp-Param-*headers for parameters a tool marks withx-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
Authorizationtoken) 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, seeMCPClient.probe_timeout (
float|None) –server/discoverprobe timeout. Defaults totimeout: 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
- 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’sinputSchemafield.annotations (
dict[str,Any]) – The tool’sannotationsobject (behavior hints such asreadOnlyHintanddestructiveHint); empty when absent.output_schema (
dict[str,Any] |None) – The tool’soutputSchema, orNonewhen the tool declares none. Results must then carry conformingstructuredContent.
- Parameters:
- class toolscore.mcp.MCPToolResult(content, is_error, raw, duration, input_required=False)[source]
The outcome of a
tools/callinvocation.- Variables:
content (
Any) – The parsedcontentlist from the call result (or the raw error payload when the call failed at the JSON-RPC level).is_error (
bool) –Trueif the result reportedisErroror the response was a JSON-RPC error.duration (
float) – Wall-clock seconds measured client-side for the round trip.input_required (
bool) –Truewhen the server answered withresultType: "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.contentthen says what the server asked for.
- Parameters:
- property input_requests: list[str]
The methods the server asked for (
elicitation/create…), when input is required.
- 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.
- toolscore.mcp.content_to_text(content)[source]
Render MCP
contentas the text an MCP client would give to a model.- Parameters:
content (
Any) – Thecontentvalue of atools/callresult (normally a list of content items). A plain string is returned unchanged, and a JSON-RPC error object yields itsmessage.- Returns:
textas-is; an embedded textresourceas[resource <uri>]followed by its body; a binary resource,imageoraudioas a bracketed placeholder with its MIME type; aresource_linkas[resource link <uri> <name>]. Unknown item types are skipped.- Return type:
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/calltraffic.- Parameters:
Example
>>> recorder = MCPRecorder(["python", "server.py"], Path("session.json")) >>> exit_code = recorder.run() # relays stdin/stdout until the client disconnects
- calls_recorded
Number of completed tool calls recorded so far.
- run(stdin=None, stdout=None, stderr=None)[source]
Relay a whole session and return the server’s exit code.
Reads client messages from
stdinuntil it closes, relays server output tostdoutuntil the server exits, and passes the server’s stderr through. The trace is written at the end even if no tool was called.- Parameters:
- Return type:
- 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.
- classmethod from_mapping(data)[source]
Build a spec from parsed JSON/YAML.
- Raises:
ValueError – On an unknown key or a malformed rule.
- Return type:
- Parameters:
data (Any)
- 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;Nonefor 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 fordelay.max_chars (
int) – Characters kept bytruncate.forward (
bool|None) – Whether the call reaches the server;Nonefor the fault’s default.target_tool (
str|None) – Forprompt_injection: the tool the planted instruction asks the agent to call.canary (
str|None) – Forprompt_injection: the token planted with the instruction;Nonederives a unique one from the seed, tool and call number.
- Parameters:
- __post_init__()[source]
Validate the rule.
- Raises:
ValueError – On an unknown fault or an out-of-range value.
- Return type:
- __init__(fault, tools=<factory>, calls=None, probability=1.0, message=None, seconds=1.0, max_chars=40, forward=None, target_tool=None, canary=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')
- class toolscore.mcp.faults.Injection(rule, tool, tool_call, seed=0)[source]
A fault chosen for one call.
- Variables:
- Parameters:
- synthesize(request_id, modern)[source]
The response sent instead of the server’s (
Nonefortimeout).
- toolscore.mcp.faults.FAULT_KINDS = ('error', 'jsonrpc_error', 'warning', 'empty', 'delay', 'timeout', 'disabled', 'denied', 'truncate', 'prompt_injection')
Every fault kind the proxy can inject.
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 undermcpServers/serversidentifying 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, orNonefor 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:
- 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 (mcpServersor VS Codeserverslayout).server (
str|None) – Name of the server to load. IfNoneand exactly one server is defined, that server is used. IfNoneand multiple servers exist, aValueErroris raised listing the available names.
- Return type:
- Returns:
The resolved
MCPServerSpec.- Raises:
FileNotFoundError – If
pathdoes not exist.ValueError – If the file is malformed, the server mapping is missing or empty, the requested
serveris not found,serverisNonewhile 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:
spec (
MCPServerSpec) – The resolved server entry.timeout (
float) – Per-request timeout in seconds.protocol (
Literal['auto','modern','legacy']) –"auto","modern"or"legacy"(seetoolscore.mcp.client.MCPClient).
- Return type:
- Returns:
An
MCPHttpClientfor aurlentry, otherwise anMCPStdioClient.
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_toolhappy-path scenarios (well-formed arguments generated viagenerate_value_from_schema(), with all required properties present) and, wheninclude_edge_casesis 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(--argvalues) 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:
tools (
list[MCPToolDef]) – The tool definitions to plan scenarios for.cases_per_tool (
int) – Number of happy-path scenarios per tool.include_edge_cases (
bool) – Whether to also generate edge-case scenarios.fixtures (
ArgumentFixtures|None) – Known-good argument values, seetoolscore.mcp.fixtures.ArgumentFixtures.
- Return type:
- 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
okdetermination depends on the scenario kind:"happy"scenarios areokonly if the call completed without an error result."edge"scenarios areokwhenever 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:
- Return type:
- Returns:
One
ScenarioResultper 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
requiredthat is absent fromproperties.
Warnings (ergonomic nits):
missing or very short (< 10 chars) description,
a tool name that is not
snake_case,properties present but no
requiredlist 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(seetoolscore.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
fixhint. Issues found in the instructions are reported under the tool name"<instructions>".- Parameters:
tools (
list[MCPToolDef]) – The tool definitions to lint.instructions (
str|None) – The server’sinstructionsfrom the initialize result (MCPClient.server_instructions), if any.
- Return type:
- 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_caseorkebab-case, so fields such asendCursorand values such asaddare not read as tools); or an unquotedsnake_casename 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 asget_commentsare often values of amethodparameter).
- 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.
- 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 neitherreadOnlyHintnordestructiveHint.annotation-read-only-contradiction:readOnlyHint: trueon a tool whose name says it deletes or writes (for exampledelete_file).annotation-hints-conflict:readOnlyHint: truetogether withdestructiveHint: 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:
- 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
outputSchemato returnstructuredContentconforming to it. Only happy-path calls that succeeded are checked. Validation covers a conservative subset of JSON Schema (seetoolscore.mcp.output_schema.validate_instance()): unknown keywords and$refare not judged, so a reported mismatch is real.Warnings, at most one per tool and rule:
structured-content-missing: a successful result has nostructuredContent.structured-content-mismatch:structuredContentdoes not conform.
- Parameters:
tools (
list[MCPToolDef]) – The server’s tools.results (
list[ScenarioResult]) – The executed scenario results.
- Return type:
- Returns:
The issues found.
- toolscore.mcp.output_schema.validate_instance(value, schema)[source]
Validate
valueagainstschemaand return readable errors.- Parameters:
- Return type:
- 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 owninputSchema(fromvalidate_instance()); empty when the schema accepts them (an empty string can be valid).
- Parameters:
- 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 withoutis_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’sstructuredContent(Nonewhen absent or when the call failed).has_structured_content (
bool) – Whether the result carriedstructuredContent.input_required (
bool) – The server answeredresultType: "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.okisFalse; usestatus.input_requests (
list[str]) – The methods the server asked for (elicitation/create…).
- Parameters:
- property accepted_invalid_input: bool
An edge case whose arguments break the input schema, answered as a success.
The server returned a result without
isErrorfor arguments its owninputSchemarejects (a missing required argument, a wrong type…). Either it accepted invalid input, or it reported the rejection withoutisError, 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>)
- 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:
Argument values
- class toolscore.mcp.ArgumentFixtures(shared=dict(), per_tool=dict(), raw=dict())[source]
Argument values a server is known to accept.
- Variables:
- Parameters:
- raw: dict[str, dict[str, str]]
The text of
--argvalues as typed, by scope ("*"or a tool) and name.
- classmethod from_mapping(data)[source]
Build fixtures from
{"*": {...}, "<tool>": {...}}.- Parameters:
data (
Any) – The parsed fixture mapping.- Return type:
- Returns:
The fixtures.
- Raises:
ValueError – If
dataor a section is not a mapping.
- classmethod from_options(options)[source]
Build fixtures from
--argoption values (seeparse_arg()).- Return type:
- Parameters:
- merged(other)[source]
A copy with
other’s values on top of these.- Return type:
- 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:
- Parameters:
tool (MCPToolDef)
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 (fromMCPClient.list_tools()).config (
ProbeConfig|None) – Declared pairs, relations and argument values;Noneprobes 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’sargs.
- Return type:
- Returns:
One
ProbeResultper 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 (seePROBE_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_errorand a shortexcerptof the result.check – What was checked within the probe: the bound parameter, or the declared relation’s
id; empty for round trips.
- Parameters:
- property severity: str | None
"error"for a high-confidence failure,"warning"for others, elseNone.
- 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.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)
pairs (list[RoundTripPair])
relations (list[BoundRelation])
- args: ArgumentFixtures
- pairs: list[RoundTripPair]
- relations: list[BoundRelation]
- 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:
- Parameters:
data (Any)
- __init__(args=<factory>, builtins=True, writes=<factory>, exclude=<factory>, pairs=<factory>, relations=<factory>, agreements=<factory>, idempotent=<factory>)
- Parameters:
args (ArgumentFixtures)
builtins (bool)
pairs (list[RoundTripPair])
relations (list[BoundRelation])
- 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:
- class toolscore.mcp.BoundRelation(tool, param, values, expect='exact', args=dict(), unit='auto', id='')[source]
A declared bound:
param = Nmust return at most (or exactly) N lines or items.- Variables:
tool (
str) – The tool.param (
str) – The bound parameter.expect (
str) –"at_most","exact"(min(N, all)),"prefix"or"suffix"(exact, and the start/end of the full content).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:
- class toolscore.mcp.Agreement(left, right, expect='subset', id='')[source]
Two calls whose items should agree (
leftwithinright, or equal).- Variables:
- Parameters:
- class toolscore.mcp.CallSpec(tool, args=dict(), field=None)[source]
One tool call in a declared relation.
- toolscore.mcp.load_probe_config(path)[source]
Read a probe config file (JSON, or YAML with PyYAML installed).
- Return type:
- 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/tailinteger 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 readlimit: 0as “no limit”.- Return type:
- Parameters:
tool (MCPToolDef)
fixtures (ArgumentFixtures)
- 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:
- Parameters:
tool (MCPToolDef)
- toolscore.mcp.probes.write_basis(tool)[source]
Why a tool counts as a write tool for round trips, or
Noneif it does not.- Return type:
- Parameters:
tool (MCPToolDef)
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]) – TheserverInfodict 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 serverinstructionsfrom 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"(initializehandshake), if known.probes (
list[ProbeResult] |None) – Effect-probe results, orNonewhen probes did not run (seetoolscore.mcp.probes).probe_grade_cap – Cap the grade at
PROBE_GRADE_CAPwhen a high-confidence probe failed (the default). The score is unchanged.
- Parameters:
tools (list[MCPToolDef])
results (list[ScenarioResult])
instructions (str | None)
protocol_version (str | None)
era (str | None)
probes (list[ProbeResult] | None)
probe_grade_cap (bool)
- tools: list[MCPToolDef]
- results: list[ScenarioResult]
- probes: list[ProbeResult] | None = None
- 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.0if none).
- property effect_rate: float | None
Share of high-confidence probe checks that passed.
Nonewhen 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
Nonewhen probes did not run.passandfail(any confidence);unknowncounts inconclusive probes (they could not run, so they are not a pass);skippedcounts probes that were not run (writes not allowed).
- 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_CAPor worse.
- property grade_capped: bool
Whether
gradeis lower thanuncapped_gradebecause of the 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 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:
tools (list[MCPToolDef])
results (list[ScenarioResult])
instructions (str | None)
protocol_version (str | None)
era (str | None)
probes (list[ProbeResult] | None)
probe_grade_cap (bool)
- 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:
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:Truewith heuristics only, or aProbeConfig.None/Falseskips 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:
- Returns:
The scorecard.
- toolscore.mcp.grade_meets(grade, threshold)[source]
Report whether
gradeis at least as good asthreshold.
- 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:
- toolscore.mcp.scorecard_to_json(card)[source]
Render the scorecard as a JSON-serializable dict.
- Parameters:
card (
MCPScorecard) – The scorecard to render.- Return type:
- 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:
- 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.
- toolscore.mcp.badge.badge_endpoint(grade, cap_note='')[source]
The shields.io endpoint JSON for the grade.
- 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:
- Parameters:
- tools: list[MCPToolDef]
- classmethod from_client(client, source='')[source]
Snapshot a started client (lists its tools).
- Return type:
- Parameters:
- property tool_map: dict[str, MCPToolDef]
Tools by name.
- toolscore.mcp.load_snapshot(path)[source]
Read a snapshot or lock file from disk (see
snapshot_from_json()).- Return type:
- Parameters:
- toolscore.mcp.write_snapshot(path, snapshot)[source]
Write a snapshot file and return its path.
- Return type:
- Parameters:
snapshot (ServerSnapshot)
- toolscore.mcp.snapshot.snapshot_from_json(data, source='')[source]
Read a snapshot, a lock file (
toolscore mcp pin) or a rawtools/listresult.- Parameters:
- Return type:
- Returns:
The snapshot.
- Raises:
ValueError – If
dataholds no tool list.
- toolscore.mcp.verify_pin(lock, snapshot, fail_on='drift')[source]
Compare a server with its lock.
- Parameters:
lock (
dict[str,Any]) – The lock (seebuild_lock()).snapshot (
ServerSnapshot) – The live server (or a saved snapshot of it).fail_on (
str) –"drift","capability"or"never".
- Return type:
- Returns:
The
PinReport.- Raises:
ValueError – On an unknown
fail_on.
- toolscore.mcp.write_lock(path, lock)[source]
Write a lock file (indented, sorted tool names) and return its path.
- 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:
- toolscore.mcp.pin.load_capability_overrides(path)[source]
Read
{"tool": ["read", ...]}capability overrides (JSON).
- 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) – Thefail_onmode used (seeFAIL_MODES).server (
str) – The live server’s label.
- Parameters:
findings (list[PinFinding])
fail_on (str)
server (str)
- findings: list[PinFinding]
- property failing: list[PinFinding]
The findings that fail the check under
fail_on.
- __init__(findings, fail_on='drift', server='')
- Parameters:
findings (list[PinFinding])
fail_on (str)
server (str)
- Return type:
None
- class toolscore.mcp.PinFinding(rule, severity, tool, message, diff='', fields=list())[source]
One difference between a server and its lock.
- 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:
a (
ServerSnapshot) – The baseline (for example the released build).b (
ServerSnapshot) – The candidate.scorecards (
tuple[MCPScorecard,MCPScorecard] |None) – Scorecards of both sides, to compare grades and probes.
- Return type:
- 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.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--testran, elseNone.new_tool_capabilities (
dict[str,list[str]]) – Capabilities of each added tool.
- Parameters:
- changed: list[ToolChange]
- scorecards: tuple[MCPScorecard, MCPScorecard] | None = None
- property score_regressions: list[str]
A lower grade and newly failing high-confidence probes (
--testonly).
- 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).
- __init__(a, b, added=<factory>, removed=<factory>, changed=<factory>, lint_new=<factory>, lint_resolved=<factory>, server_changes=<factory>, scorecards=None, new_tool_capabilities=<factory>)
- 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…).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:
- __init__(tool, fields=<factory>, diffs=<factory>, breaking=<factory>, capabilities_added=<factory>, capabilities_removed=<factory>)
- 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:
- Parameters:
diff (ServerDiff)
color (bool)
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 underguard_denials. Declarative guards (denyrules in the forbidden-call format, anallow_toolslist) 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_estimatoror the spec) plus a worst case for the next call (the conversation so far, estimated, plusmax_output_tokens) must stay undermax_usd, or the run stops withbudget_stoppedand the study stops. A model without a known price is refused before any call unlessallow_unknown_priceis set; its cost is thennull(unknown), never 0.Limits.
max_turnsmodel calls andmax_callstool calls per run.Build verification. Each row records the server’s
serverInfoname and version and the protocol;verifyin 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:
- Parameters:
- name: str
- mcp_name: str
- description: str
- toolscore.mcp.agent.map_tools(tools, allow=None)[source]
MCP tools -> provider function tools, with safe, unique names.
- class toolscore.mcp.agent.ToolRequest(id, name, arguments, argument_error='')[source]
A tool call the model asked for.
- Variables:
- Parameters:
- id: str
- name: str
- argument_error: str = ''
- class toolscore.mcp.agent.ModelTurn(text, requests, input_tokens=None, output_tokens=None)[source]
One model response.
- Variables:
- Parameters:
- text: str
- requests: list[ToolRequest]
- class toolscore.mcp.agent.ModelProvider(*args, **kwargs)[source]
A conversation with one model. One instance per run.
startsets up the conversation,completeasks the model for its next turn,add_resultsgives it the tool results, andestimated_input_tokenssizes the next request for the budget check.- provider: str
- model: str
- max_output_tokens: int
- start(system, prompt, tools)[source]
Begin the conversation.
- 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.
- __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:
- provider = 'openai'
- __init__(client, model, max_output_tokens=1024, extra=None)[source]
- start(system, prompt, tools)[source]
- complete()[source]
- Return type:
ModelTurn
- add_results(turn, results)[source]
- class toolscore.mcp.agent.AnthropicMessagesProvider(client, model, max_output_tokens=1024, extra=None)[source]
Anthropic Messages (
client.messages.create).- Parameters:
- provider = 'anthropic'
- __init__(client, model, max_output_tokens=1024, extra=None)[source]
- start(system, prompt, tools)[source]
- complete()[source]
- Return type:
ModelTurn
- add_results(turn, results)[source]
- 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": "..."}(callsoptional). A step without calls ends the run with itstextas the final answer. Usage is reported frominput_tokens/output_tokensin a step, else estimated.- Parameters:
- provider = 'scripted'
- __init__(script, model='scripted')[source]
- start(system, prompt, tools)[source]
- complete()[source]
- Return type:
ModelTurn
- add_results(turn, results)[source]
- 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.
- tool: str
- task_id: str = ''
- arm_id: str = ''
- index: int = 0
- class toolscore.mcp.agent.GuardDecision(allowed, reason='')[source]
What a guard decided:
allowed, and thereasonfor a denial.- allowed: bool
- reason: str = ''
- toolscore.mcp.agent.allow()[source]
Let the call through.
- Return type:
- toolscore.mcp.agent.deny(reason)[source]
Block the call; the agent gets a tool error with
reason.- Return type:
- Parameters:
reason (str)
- toolscore.mcp.agent.rules_guard(deny_rules=None, allow_tools=None)[source]
A declarative guard.
- Parameters:
- Return type:
- Returns:
The guard.
- exception toolscore.mcp.agent.UnknownPriceError[source]
A model has no known price and
allow_unknown_priceis not set.
- class toolscore.mcp.agent.Price(input, output, source)[source]
USD per 1M input and output tokens, and where the price came from.
- input: float
- output: float
- source: str
- toolscore.mcp.agent.price_for(model, pricing=None)[source]
The price of a model:
pricingfrom the spec, else the built-in table, elseNone.
- 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:
- 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
Nonewhen the price or the usage is unknown.
- projected(price, provider)[source]
Spent so far plus the worst case of the next request.
- Return type:
- Parameters:
price (Price)
provider (ModelProvider)
- allows(price, provider)[source]
Whether the next model call fits under the cap.
- Return type:
- Parameters:
price (Price | None)
provider (ModelProvider)
- class toolscore.mcp.agent.Limits(max_turns=10, max_calls=20)[source]
Per-run limits: model calls (
max_turns) and tool calls (max_calls).- max_turns: int = 10
- max_calls: int = 20
- 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
- structured: Any = None
- is_error: bool = False
- denied: bool = False
- __init__(id, tool, provider_name, args, result=None, structured=None, is_error=False, error=None, duration=None, denied=False, deny_reason=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.turns (
int) – Model calls made.input_tokens (
int|None) – Reported input tokens (Noneif a turn did not report).cost_usd (
float|None) – Cost of the run, orNonewhen unknown.stop_reason (
str) – Why the run stopped.duration_s (
float) – Wall-clock seconds.
- Parameters:
- status: str
- calls: list[CallRecord]
- turns: int
- stop_reason: str
- duration_s: float = 0.0
- trace()[source]
The calls as Toolscore trace dicts (denied calls are failed calls).
- __init__(status, calls, final_answer, turns, input_tokens, output_tokens, cost_usd, stop_reason, error=None, duration_s=0.0)
- 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.guard (
Any) –guard(GuardCall) -> allow() | deny(reason)(seerules_guard()).budget (
Budget|None) – A sharedBudget, checked before every model call.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:
- Returns:
The
AgentRun. Provider and server errors end the run withstatus="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
- max_output_tokens: int = 1024
- 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
- min_score: float = 0.9
- require_completed: bool = True
- script_for(arm_id)[source]
The scripted turns for an arm:
scriptitself, orscript[arm_id]when keyed by arm.
- __init__(id, prompt, expected=None, forbidden=None, min_score=0.9, script=None, require_completed=True)
- 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.rstfor the file format.- Parameters:
- name: str
- arms: list[ArmSpec]
- tasks: list[TaskSpec]
- repetitions: int = 1
- seed: int = 0
- limits: Limits
- base_dir: str = '.'
- cells()[source]
Every (task, arm, repetition), interleaved in a shuffled order fixed by
seed.
- __init__(name, server, arms, tasks, repetitions=1, seed=0, budget=<factory>, limits=<factory>, guard=<factory>, verify=<factory>, allow_tools=None, output=None, base_dir='.')
- toolscore.mcp.agent.spec_from_mapping(data, base_dir='.')[source]
Validate and build an
AgentSpecfrom parsed YAML/JSON.- Raises:
ValueError – On a missing or unknown key, or a value of the wrong type.
- Return type:
- Parameters:
- toolscore.mcp.agent.load_agent_spec(path)[source]
Read an agent spec (YAML with
tool-scorer[yaml], or JSON).
- 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
serverInfoagainstverify.server_name/verify.server_version.Values are compared exactly, or as a regex when written
/.../.
- toolscore.mcp.agent.run_version_command(verify, cwd='.')[source]
Run
verify.commandand match its output againstverify.expect.
- 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:
- 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 (unlessrequire_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 iserror; a task with no expected or forbidden calls isunknownunless an honesty error makes itfail.
- 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
- skipped: int
- stopped: str
- spent_usd: float
- unknown_cost_turns: int
- toolscore.mcp.agent.completed_cells(path, retry_errors=False)[source]
Cell IDs already in a JSONL output (errored ones only unless
retry_errors).
- toolscore.mcp.agent.preflight_prices(spec, allow_unknown_price=False)[source]
The price of every arm, refusing unknown prices unless allowed.
- 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’soutput, else<name>.runs.jsonl).provider_factory (
Callable[[ArmSpec,TaskSpec],ModelProvider] |None) – Creates the provider of a run (default:default_provider_factory(); tests pass fakes).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 doctorand--dry-run).Per run:
max_turnsmodel calls, each withmax_output_tokensout 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.
- 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 fromrun_study()(record: "run").tasks (
dict[str,TaskSpec] |None) – New task definitions by task ID (theirexpected,forbidden,min_scoreandrequire_completedare used); rows of other tasks keep their own.expected (
list[dict[str,Any]] |None) – New expected calls for every row (instead oftasks).
- Return type:
- Returns:
The rows with a new
evaluation,outcomeandpassed, and aregradedblock (from_sha256of 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.guard (
Any) –guard(GuardCall) -> allow() | deny(reason)(seerules_guard()).budget (
Budget|None) – A sharedBudget, checked before every model call.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:
- Returns:
The
AgentRun. Provider and server errors end the run withstatus="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’soutput, else<name>.runs.jsonl).provider_factory (
Callable[[ArmSpec,TaskSpec],ModelProvider] |None) – Creates the provider of a run (default:default_provider_factory(); tests pass fakes).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).
- toolscore.mcp.agent.spec_from_mapping(data, base_dir='.')[source]
Validate and build an
AgentSpecfrom parsed YAML/JSON.- Raises:
ValueError – On a missing or unknown key, or a value of the wrong type.
- Return type:
- 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 fromrun_study()(record: "run").tasks (
dict[str,TaskSpec] |None) – New task definitions by task ID (theirexpected,forbidden,min_scoreandrequire_completedare used); rows of other tasks keep their own.expected (
list[dict[str,Any]] |None) – New expected calls for every row (instead oftasks).
- Return type:
- Returns:
The rows with a new
evaluation,outcomeandpassed, and aregradedblock (from_sha256of 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 (unlessrequire_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 iserror; a task with no expected or forbidden calls isunknownunless an honesty error makes itfail.
- toolscore.mcp.agent.estimate_study_cost(spec, prices)[source]
A worst-case cost estimate before any call (for
toolscore doctorand--dry-run).Per run:
max_turnsmodel calls, each withmax_output_tokensout 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.
- toolscore.mcp.agent.preflight_prices(spec, allow_unknown_price=False)[source]
The price of every arm, refusing unknown prices unless allowed.
- toolscore.mcp.agent.check_build(server_info, verify)[source]
Check
serverInfoagainstverify.server_name/verify.server_version.Values are compared exactly, or as a regex when written
/.../.
- toolscore.mcp.agent.map_tools(tools, allow=None)[source]
MCP tools -> provider function tools, with safe, unique names.
- toolscore.mcp.agent.rules_guard(deny_rules=None, allow_tools=None)[source]
A declarative guard.
- Parameters:
- Return type:
- Returns:
The guard.
- toolscore.mcp.agent.deny(reason)[source]
Block the call; the agent gets a tool error with
reason.- Return type:
- 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:
- provider = 'openai'
- class toolscore.mcp.agent.AnthropicMessagesProvider(client, model, max_output_tokens=1024, extra=None)[source]
Anthropic Messages (
client.messages.create).- Parameters:
- provider = 'anthropic'
- 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": "..."}(callsoptional). A step without calls ends the run with itstextas the final answer. Usage is reported frominput_tokens/output_tokensin a step, else estimated.- Parameters:
- provider = 'scripted'
- class toolscore.mcp.agent.ModelProvider(*args, **kwargs)[source]
A conversation with one model. One instance per run.
startsets up the conversation,completeasks the model for its next turn,add_resultsgives it the tool results, andestimated_input_tokenssizes the next request for the budget check.- __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.turns (
int) – Model calls made.input_tokens (
int|None) – Reported input tokens (Noneif a turn did not report).cost_usd (
float|None) – Cost of the run, orNonewhen unknown.stop_reason (
str) – Why the run stopped.duration_s (
float) – Wall-clock seconds.
- Parameters:
- __init__(status, calls, final_answer, turns, input_tokens, output_tokens, cost_usd, stop_reason, error=None, duration_s=0.0)
- 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.rstfor the file format.- Parameters:
- __init__(name, server, arms, tasks, repetitions=1, seed=0, budget=<factory>, limits=<factory>, guard=<factory>, verify=<factory>, allow_tools=None, output=None, base_dir='.')
- 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:
- turn_cost(price, turn)[source]
The cost of one turn, or
Nonewhen the price or the usage is unknown.
- projected(price, provider)[source]
Spent so far plus the worst case of the next request.
- Return type:
- Parameters:
price (Price)
provider (ModelProvider)
- allows(price, provider)[source]
Whether the next model call fits under the cap.
- Return type:
- Parameters:
price (Price | None)
provider (ModelProvider)
- class toolscore.mcp.agent.Limits(max_turns=10, max_calls=20)[source]
Per-run limits: model calls (
max_turns) and tool calls (max_calls).
- class toolscore.mcp.agent.Price(input, output, source)[source]
USD per 1M input and output tokens, and where the price came from.
- 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.
- class toolscore.mcp.agent.GuardDecision(allowed, reason='')[source]
What a guard decided:
allowed, and thereasonfor a denial.