Spaces:
Running
Running
File size: 12,181 Bytes
fd5dd94 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 | """Consume external MCP servers as tenant tools, with pinned definition hashes.
* **Connect** by URL over Streamable HTTP (``mcp.Client``). Auth is a bearer token resolved
from the connection's secret ref at call time. The user's WorkPilot token is *never*
forwarded (no token passthrough): the only credential an MCP server sees is the one the
tenant registered for it.
* **Import**: each server tool becomes a tenant tool ``<connection>.<tool>``. The suggested
tier comes from the tool annotations (``readOnlyHint`` -> T0; ``destructiveHint: false``
-> T2; anything else, including the MCP default ``destructiveHint: true``, -> T3). Like
every tenant tool it runs as T3/test until an owner confirms it.
* **Pinning (rug-pull defense)**: the hash of each upstream definition (name, description,
input schema, annotations) is pinned at confirmation. ``refresh`` reports added, changed
and removed tools; a changed tool is blocked (``pending``) until an owner re-confirms. The
handler re-checks the live definition before *every* call and refuses on mismatch, so a
server that swaps a definition between refreshes still cannot run the new one.
* Server-provided text (descriptions, results) is untrusted: descriptions are cleaned and
capped, results carry ``"untrusted": True``.
"""
from __future__ import annotations
import uuid
from collections.abc import Callable
from contextlib import AbstractAsyncContextManager
from datetime import UTC, datetime
from typing import Any, Literal
from pydantic import BaseModel
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from core.config import get_settings
from core.mcp.models import McpConnection
from core.tools.http_tool import check_url
from core.tools.jsonschema_model import SchemaError, model_from_schema
from core.tools.openapi_import import _snake, clean_text, resolve
from core.tools.preview import canonical_json, preview_hash, sha256_hex
from core.tools.spec import RiskTier, ToolContext, ToolHandler, ToolResult
from core.tools.tenant_tools import HandlerEnv, ImportReport, NewTool, TenantTool, TenantToolStore
# (url, headers) -> async context manager yielding an ``mcp.Client``-like object with
# ``list_tools()`` and ``call_tool(name, arguments)``.
Connect = Callable[[str, dict[str, str]], AbstractAsyncContextManager[Any]]
class McpError(RuntimeError):
pass
def default_connect(url: str, headers: dict[str, str]) -> AbstractAsyncContextManager[Any]:
from mcp import Client
from mcp.client.streamable_http import ( # type: ignore[attr-defined]
create_mcp_http_client,
streamable_http_client,
)
check_url(url)
http = create_mcp_http_client(headers=headers)
return Client(streamable_http_client(url, http_client=http))
def server_origin(url: str) -> str:
from urllib.parse import urlsplit
u = urlsplit(url)
return f"{u.scheme}://{(u.hostname or '').lower()}:{u.port or ''}"
def auth_headers(auth_type: str, secret: str | None) -> dict[str, str]:
if auth_type == "none" or not secret:
return {}
return {"Authorization": f"Bearer {secret}"}
def _dump(model: Any) -> dict[str, Any]:
if model is None:
return {}
if isinstance(model, BaseModel):
return model.model_dump(mode="json", exclude_none=True)
return dict(model)
def upstream_definition(tool: Any) -> dict[str, Any]:
return {
"name": tool.name,
"description": tool.description or "",
"input_schema": _dump(getattr(tool, "input_schema", None)),
"annotations": _dump(getattr(tool, "annotations", None)),
}
def upstream_hash(tool: Any) -> str:
return sha256_hex(canonical_json(upstream_definition(tool)))
def suggested_tier(annotations: dict[str, Any]) -> int:
if annotations.get("read_only_hint") is True:
return int(RiskTier.T0_READ)
if annotations.get("destructive_hint") is False:
return int(RiskTier.T2_EXTERNAL)
return int(RiskTier.T3_CRITICAL)
def _input_schema(raw: dict[str, Any]) -> dict[str, Any]:
schema = resolve(raw, raw) if raw else {}
schema = {k: v for k, v in schema.items() if k not in ("$defs", "definitions")}
schema.setdefault("type", "object")
schema.setdefault("properties", {})
return schema
def to_new_tools(conn: McpConnection, listed: list[Any]) -> list[NewTool]:
out: list[NewTool] = []
limit = get_settings().ext_max_tools_per_import
for t in listed[:limit]:
defn = upstream_definition(t)
schema = _input_schema(defn["input_schema"])
name = f"{conn.name}.{_snake(t.name)}"[:200]
try:
model_from_schema(schema, name)
except SchemaError:
schema = {"type": "object", "properties": {}}
h = upstream_hash(t)
out.append(
NewTool(
name=name,
description=clean_text(defn["description"] or t.name),
input_schema=schema,
kind="mcp",
config={
"connection_id": str(conn.id),
"tool": t.name,
"upstream_hash": h,
"payments": bool(getattr(conn, "payment_capable", False)),
},
suggested_tier=suggested_tier(defn["annotations"]),
definition_hash=h,
secret_ref=conn.secret_ref,
)
)
return out
class McpService:
def __init__(self, store: TenantToolStore, connect: Connect | None = None) -> None:
self.store = store
self.connect: Connect = connect or store.mcp_connect or default_connect
async def list_remote(self, url: str, auth_type: str, secret_ref: str | None) -> list[Any]:
secret = self.store.secrets.get(secret_ref) if secret_ref else None
if auth_type != "none" and not secret:
raise McpError(f"secret {secret_ref!r} is not set")
try:
async with self.connect(url, auth_headers(auth_type, secret)) as client:
return list((await client.list_tools()).tools)
except McpError:
raise
except Exception as exc:
raise McpError(f"MCP server unreachable: {type(exc).__name__}: {exc}") from exc
async def sync(
self, session: AsyncSession, conn: McpConnection, listed: list[Any]
) -> ImportReport:
report = await self.store.sync(
session, conn.tenant_id, to_new_tools(conn, listed), source="mcp", source_id=conn.id
)
conn.status = "changed" if report.changed else "ok"
if report.changed: # Phase 15: a pinned definition changed upstream -> alert
await self._alert_changed(session, conn, report.changed)
conn.last_refreshed_at = datetime.now(UTC)
conn.last_diff = {
"created": report.created,
"changed": report.changed,
"removed": report.removed,
"unchanged": report.unchanged,
}
conn.updated_at = datetime.now(UTC)
return report
@staticmethod
async def _alert_changed(
session: AsyncSession, conn: McpConnection, changed: list[str]
) -> None:
from core.observability.alerts import AlertCandidate, record
digest = sha256_hex(canonical_json(sorted(changed)))[:16]
await record(
session,
[
AlertCandidate(
conn.tenant_id,
"mcp_definition_changed",
"warning",
f"MCP server {conn.name} changed {len(changed)} pinned tool definition(s); "
"they are blocked until an owner re-confirms",
f"mcp_changed:{conn.id}:{digest}",
{"connection": conn.name, "tools": changed[:50]},
)
],
)
@staticmethod
async def check_secret_scope(
session: AsyncSession, secret_ref: str | None, url: str, name: str | None = None
) -> None:
"""Per-server scoped tokens (Phase 15): one secret ref may authenticate only one MCP
server origin, so a token issued for server A is never presented to server B."""
if not secret_ref:
return
origin = server_origin(url)
rows = await session.execute(
select(McpConnection.name, McpConnection.url).where(
McpConnection.secret_ref == secret_ref
)
)
for other_name, other_url in rows.all():
if other_name != name and server_origin(other_url) != origin:
raise McpError(
f"secret {secret_ref!r} already authenticates MCP server "
f"{other_name!r}; register a token scoped to this server"
)
@staticmethod
async def by_name(session: AsyncSession, name: str) -> McpConnection | None:
return (
await session.execute(select(McpConnection).where(McpConnection.name == name))
).scalar_one_or_none()
def _result_text(result: Any, limit: int) -> tuple[str, bool]:
parts = [getattr(c, "text", "") for c in (result.content or [])]
text = "\n".join(p for p in parts if p)
return text[:limit], len(text) > limit
def mcp_handler_factory(row: TenantTool, env: HandlerEnv) -> ToolHandler:
config = dict(row.config)
upstream = str(config["tool"])
pinned = str(config["upstream_hash"])
connection_id = uuid.UUID(str(config["connection_id"]))
test_mode = env.test_mode
async def handler(params: BaseModel, ctx: ToolContext) -> ToolResult:
args = params.model_dump(mode="json", by_alias=True, exclude_none=True)
if ctx.dry_run:
preview = {"mcp_tool": upstream, "arguments": args}
return ToolResult(
ok=True, dry_run=True, data=preview, preview_hash=preview_hash(preview)
)
if test_mode:
return ToolResult(ok=False, error="tool is in test mode: only dry runs are allowed")
conn = await ctx.session.get(McpConnection, connection_id)
if conn is None or not conn.enabled:
return ToolResult(ok=False, error="MCP connection is missing or disabled")
headers = auth_headers(conn.auth_type, ctx.credentials.get("secret"))
if conn.auth_type != "none" and not headers:
return ToolResult(ok=False, error="credential for this MCP server is not configured")
connect: Connect = env.mcp_connect or default_connect
limit = get_settings().ext_max_response_bytes
try:
async with connect(conn.url, headers) as client:
listed = {t.name: t for t in (await client.list_tools()).tools}
live = listed.get(upstream)
if live is None:
return ToolResult(ok=False, error=f"MCP server no longer offers {upstream}")
if upstream_hash(live) != pinned:
return ToolResult(
ok=False,
error="tool definition changed on the MCP server since it was confirmed "
"(refused: refresh the connection and re-confirm)",
)
result = await client.call_tool(upstream, args)
except Exception as exc:
return ToolResult(ok=False, error=f"MCP call failed: {type(exc).__name__}")
text, truncated = _result_text(result, limit)
data = {
"content": text,
"structured": getattr(result, "structured_content", None),
"truncated": truncated,
"untrusted": True,
}
if getattr(result, "is_error", False):
return ToolResult(ok=False, data=data, error="MCP tool returned an error")
return ToolResult(ok=True, data=data)
return handler
AuthType = Literal["none", "bearer"]
|