Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
72 changes: 72 additions & 0 deletions docs/agents/federation.md
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,78 @@ federation = AgentFederation(
- `discover(*, tools=None, tags=None, min_capacity=None, healthy_only=True) -> list[AgentMetadata]` — list agents matching filters
- `select_agent(*, strategy=None, tags=None, tools=None, min_capacity=None, healthy_only=True) -> AgentMetadata` — select one agent using the routing strategy
- `async run(prompt: str, *, agent_id=None, strategy=None, tags=None, tools=None, min_capacity=None, healthy_only=True, **kwargs) -> Any` — select an agent and dispatch the prompt
- `async negotiate(initial: NegotiationMessage, *, max_rounds=10, deliver_terminal=True) -> Negotiation` — exchange bounded price/SLA offers between two registered clients

## Price and SLA negotiation

Negotiation is an explicit operation; accepted agreements can optionally be supplied to sealed-bid market routing as described below. Both agents must already be registered, healthy, and provide a client implementing `negotiate(message)`. `BoundedNegotiationPolicy` makes deterministic decisions against each participant's own reservation bounds:

```python
import asyncio
from decimal import Decimal
from synapsekit.agents import (
AgentFederation, AgentMetadata, BoundedNegotiationPolicy,
NegotiationMessage, NegotiationMessageKind, NegotiationRole, NegotiationTerms,
)

def terms(price, latency_ms, availability):
return NegotiationTerms(
Decimal(price), "USD", Decimal(latency_ms), Decimal(availability), Decimal("3600")
)

buyer_policy = BoundedNegotiationPolicy(
NegotiationRole.BUYER, terms("15", "200", "99.9")
)
seller_policy = BoundedNegotiationPolicy(
NegotiationRole.SELLER, terms("12", "150", "99.95")
)

class Participant:
def __init__(self, policy, role):
self.policy = policy
self.role = role
self.terminal = None

async def run(self, prompt, **kwargs):
return prompt # Normal execution is separate from negotiation.

async def negotiate(self, message):
can_counter = self.role == NegotiationRole.SELLER
return self.policy.respond(
message,
message_id=f"{message.message_id}-response",
can_counter=can_counter,
)

async def receive_negotiation(self, message):
self.terminal = message

async def main():
buyer = Participant(buyer_policy, NegotiationRole.BUYER)
seller = Participant(seller_policy, NegotiationRole.SELLER)
federation = AgentFederation(clients={"buyer": buyer, "seller": seller})
federation.register_agent(AgentMetadata(id="buyer", model="local"))
federation.register_agent(AgentMetadata(id="seller", model="local"))
initial = NegotiationMessage(
"neg-1", "offer-1", "buyer", "seller", NegotiationMessageKind.OFFER,
terms("10", "200", "99.9"),
)
session = await federation.negotiate(initial, max_rounds=4, deliver_terminal=True)
assert session.agreement == seller_policy.reservation
assert seller.terminal.kind == NegotiationMessageKind.ACCEPT

asyncio.run(main())
```

By default, both clients must implement `receive_negotiation(message)`; the final ACCEPT or REJECT is delivered to its recipient, and delivery errors propagate. Explicit `deliver_terminal=False` selects transcript-only mode, which does not deliver the terminal response. Delivery is in-memory, not durable or exactly-once.

`NegotiationTerms` uses finite `Decimal` values: nonnegative price per task with a three-letter uppercase currency code; maximum latency in milliseconds; and availability percentage over a window in seconds. The bounded policy checks the receiving party's price/SLA bounds, counters with its reservation if permitted, or rejects. The caller must ensure its first offer meets its own limits. These terms record agreement only—no authentication, payment, measurement, SLA enforcement, or dispute resolution is provided.

### Opt-in market routing

Pass `negotiated_agreements={seller_id: accepted_session}`, `negotiation_buyer=buyer_id`, and `negotiation_requirements=buyer_terms` to `federation.run(..., strategy="market")` or `AgentSwarm.execute(...)`. In this mode only sellers with matching accepted agreements within the buyer's price/SLA bounds and market budget compete; accepted prices influence bid scoring and sealed-bid settlement estimates. Other auction types are rejected. Ordinary market routing remains unchanged when no agreements are supplied.

The caller must verify transcript authenticity, delivery, freshness, task scope and replay policy. Agreements do not prove identity or enforce payment or SLA fulfillment; the market's float estimates may be rounded, and reported actual cost may differ from the estimate.

---

Expand Down
68 changes: 68 additions & 0 deletions docs/agents/mcp-tool-scanning.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
---
sidebar_position: 7
title: "MCP tool scanning — SynapseKit Agents"
---

# MCP tool-definition scanning

MCP servers supply tool names, descriptions and schemas at runtime. The `MCPClient` scanner applies deterministic local heuristics to effective descriptions and every input-schema string key and value, including nested property descriptions and defaults. It runs without a model call and is **off by default**. Each string is scanned separately, so patterns split across fields may be missed.

## Enable the registration gate

```python
from synapsekit.mcp import MCPClient, ToolScanBlockedError
from synapsekit.mcp.pinning import ToolApprovalRequiredError, ToolDriftDetectedError

client = MCPClient(
block_on_high_severity=True,
server_id="catalog-prod",
pin_store_path="tool-pins.json",
)
try:
tools = await client.connect_stdio("example-mcp-server")
except ToolScanBlockedError as exc:
for finding in exc.report.findings:
print(finding.tool_name, finding.severity, finding.rule)
except (ToolApprovalRequiredError, ToolDriftDetectedError) as exc:
# Review the current definitions and findings before explicitly approving.
print(client.last_scan_report)
# After human review: tools = await client.approve_current_tools()
```

`server_id` and `pin_store_path` are required together when pinning is enabled. The scanner gate works with or without pinning. High-severity findings block registration and do not overwrite saved pins. Medium findings are reported but do not block. The gate scans the definitions it will register and re-scans the newly fetched definitions on approval. A scan rejection during initial connection closes the session/transport; an approval or drift exception retains it so the caller can inspect and resolve the review flow. Use `await client.close()` when finished.

## Standalone reports

```python
from synapsekit.mcp import scan_tools
from synapsekit.mcp.pinning import make_tool_definition

snapshot = make_tool_definition(
"lookup",
"Search public records",
{"type": "object", "properties": {}},
)
report = await scan_tools([snapshot])
for finding in report.findings:
print(finding.tool_name, finding.fingerprint, finding.severity, finding.rule)
```

Findings include tool name, original definition fingerprint, severity, rule ID and a short explanation; description text is not copied into the report. If a description is missing or empty, the scanner checks the adapter's effective fallback text (`MCP tool: {name}`). Tool names come from the server; escape them before logging or terminal output.

Rules flag patterns associated with instruction overrides, concealment, system/developer role spoofing, possible secret exfiltration, remote shell-script execution, and invisible/bidirectional characters. These are narrow heuristics, not a comprehensive scanner. A clean report does not prove the server or tool is safe.

## Resource limits and security boundaries

```python
from synapsekit.mcp import ToolScanLimitError, scan_tools

try:
await scan_tools(oversized_or_untrusted_tool_set)
except ToolScanLimitError:
# Reject input as a whole; scan_tools never returns a partial report.
raise
```

The gate accepts at most 256 tools, 16,384 Unicode characters per description or individual schema string, and 262,144 combined description and schema characters. It also limits schema traversal to 16,384 nodes and depth 64, bounds tool names separately, and rejects invalid JSON-like values. Exceeding a limit raises `ToolScanLimitError` and fails closed; no partial report is returned. Normalization and pattern matching run in a worker thread, while pre-snapshot validation runs on the event loop. Limits do not bound the transport response before the MCP SDK decodes it.

The scanner examines effective descriptions and input-schema strings, not manifests, server code, tool outputs, transport behavior, or names when a nonempty description is present. It may miss encoded, paraphrased, or cross-field attacks. A server can change behavior without changing its definition or fingerprint. Pinning detects definition changes; it does not prove safety or enforce server-side behavior. Review the server, restrict its permissions and network access, isolate credentials, and monitor tool calls. Calls already in flight are not cancelled when a generation is revoked.
65 changes: 42 additions & 23 deletions docs/agents/mcp.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,55 +8,74 @@ SynapseKit supports the [Model Context Protocol](https://modelcontextprotocol.io

## MCPClient

Connect to an MCP server to discover and call remote tools.
Connect to an MCP server. `connect_stdio()` and `connect_sse()` return a list of ready-to-use `BaseTool` adapters. `MCPClient` does not expose public `list_tools()` or `call_tool()` methods; pass the returned tools to an agent, as in the example below.

### Stdio transport

```python
from synapsekit import MCPClient

client = MCPClient()
await client.connect_stdio("npx", ["-y", "@modelcontextprotocol/server-filesystem", "/tmp"])

# List available tools
tools = await client.list_tools()
for t in tools:
print(t.name, t.description)
tools = await client.connect_stdio(
"npx", ["-y", "@modelcontextprotocol/server-filesystem", "/tmp"]
)
for tool in tools:
print(tool.name, tool.description)

# Call a tool
result = await client.call_tool("read_file", {"path": "/tmp/hello.txt"})
print(result)
await client.close()
```

### SSE transport

```python
client = MCPClient()
await client.connect_sse("http://localhost:8080/sse")
tools = await client.connect_sse("http://localhost:8080/sse")
for tool in tools:
print(tool.name, tool.description)

tools = await client.list_tools()
result = await client.call_tool("search", {"query": "hello"})
await client.close()
```

## MCPToolAdapter

Wrap MCP tools as `BaseTool` instances so they work with any SynapseKit agent:
`connect_stdio()` and `connect_sse()` create `MCPToolAdapter` instances for every server tool and return them as `BaseTool` values. Use those returned adapters directly; there is no `MCPToolAdapter.from_client()` factory.

```python
from synapsekit import MCPClient, MCPToolAdapter, FunctionCallingAgent
from synapsekit import FunctionCallingAgent, MCPClient, MCPToolAdapter

client = MCPClient()
await client.connect_stdio("npx", ["-y", "@modelcontextprotocol/server-filesystem", "/tmp"])
async with MCPClient() as client:
tools = await client.connect_stdio(
"npx", ["-y", "@modelcontextprotocol/server-filesystem", "/tmp"]
)
assert all(isinstance(tool, MCPToolAdapter) for tool in tools)

agent = FunctionCallingAgent(llm=llm, tools=tools)
result = await agent.run("List files in /tmp")
print(result)
```

# Wrap all MCP tools as BaseTool instances
tools = await MCPToolAdapter.from_client(client)
Each wrapped tool preserves the server-provided name, description, and parameter schema. The adapter handles serialization and deserialization automatically. Keep the client connected while the agent uses its tools; leaving the `async with` block closes the session.

# Use with any agent
agent = FunctionCallingAgent(llm=llm, tools=tools)
result = await agent.run("List files in /tmp")
## Tool-description scanning and pinning

MCP tool descriptions come from an external server. `MCPClient` can apply a local heuristic scanner before registering tools:

```python
from synapsekit.mcp import MCPClient, ToolScanBlockedError

client = MCPClient(block_on_high_severity=True) # opt-in; default is False
try:
tools = await client.connect_stdio("example-mcp-server")
except ToolScanBlockedError as exc:
for finding in exc.report.findings:
print(finding.tool_name, finding.severity, finding.rule)
```

Each wrapped tool preserves the original name, description, and parameter schema from the MCP server. The adapter handles serialization and deserialization automatically.
The scanner reports patterns associated with instruction overrides, role spoofing, concealment, secret transfer, remote script execution, and hidden characters. High-severity findings block the whole registration; medium findings are reported but do not block. When enabled, the scanner also checks the exact definitions again during approval and blocks registration before writing pins. A blocked initial connection is closed. `ToolApprovalRequiredError` and `ToolDriftDetectedError` retain the connection for review; inspect the pending definitions and `client.last_scan_report` before calling `approve_current_tools()`.

For persistent definition pins, configure both `server_id` and `pin_store_path`; pins detect changes but do not determine whether a definition is malicious. The scan covers effective descriptions and input-schema string keys and values, including nested descriptions. It limits tools, text size, schema nodes and depth. Limit violations fail closed. Pattern matching runs off the event loop, but limits do not bound the MCP transport response before decoding.

This is heuristic analysis of tool text—not a full manifest, server-code, or runtime audit. A clean scan or matching pin does not prove safety, and server behavior can change without its definition changing. Review the server, restrict its permissions and network access, isolate credentials, and monitor calls. See [scanner behavior and limitations](./mcp-tool-scanning) for rule details.

## MCPServer

Expand Down
6 changes: 6 additions & 0 deletions docs/api/evaluation.md
Original file line number Diff line number Diff line change
Expand Up @@ -226,6 +226,12 @@ sk eval --tag rag --threshold 0.8

---

## Evaluation helpers

The API also exports `RulerGroup`, `RulerTrajectory`, `RulerScorer`, and `LLMRulerJudge` for relative scoring of same-task rollout groups; see [Relative trajectory rewards](../evaluation/ruler-rewards). Calibration utilities include the diagnostic `calibrate()` report and the opt-in `fit_calibration()` isotonic model. A scorer test fixture is not evidence of real-model performance.

For provider-free multi-turn testing, `SimulationHarness`, `BookingEnvironment`, `BookingAction`, and `Reward` are exported here. See [Seeded user simulation](../evaluation/simulation) for shared-state episodes and policy-based rewards.

## See also

- [Evaluation overview](../evaluation/overview)
Expand Down
42 changes: 27 additions & 15 deletions docs/cookbook/agent-patterns.md
Original file line number Diff line number Diff line change
Expand Up @@ -326,25 +326,37 @@ print(result.output)
Connect your agent to an external tool server using the Model Context Protocol.

```python
import asyncio
import os

from synapsekit.agents import FunctionCallingAgent
from synapsekit.agents.mcp import MCPClient
from synapsekit.llms.anthropic import AnthropicLLM
from synapsekit.llm.openai import OpenAILLM
from synapsekit.llm.base import LLMConfig
from synapsekit.mcp import MCPClient


async def main():
llm = OpenAILLM(
LLMConfig(
model="gpt-5.4-mini",
api_key=os.environ["OPENAI_API_KEY"],
provider="openai",
)
)

# Connect to a local or remote MCP server
mcp = MCPClient(server_url="http://localhost:3000/mcp")
await mcp.connect()
# Start an SSE MCP server at this address.
async with MCPClient() as mcp:
tools = await mcp.connect_sse("http://localhost:8080/sse")
agent = FunctionCallingAgent(
llm=llm,
tools=tools,
max_iterations=10,
)
result = await agent.run("List all open GitHub issues labeled 'bug'")
print(result)

tools = await mcp.list_tools() # discover available tools

agent = FunctionCallingAgent(
llm=AnthropicLLM(model="claude-3-5-sonnet-20241022"),
tools=tools,
max_steps=10,
)

result = await agent.run("List all open GitHub issues labeled 'bug'")
print(result.output)
await mcp.disconnect()
asyncio.run(main())
```

---
Expand Down
Loading
Loading