"""WorkPilot "Shopify Admin" MCP server (MCP Python SDK v2, ``MCPServer``, spec 2026-07-28). Exposes the e-commerce pack's tools to any MCP client (Claude Desktop, IDEs, other agents). It is a thin adapter: **every call goes through the WorkPilot Tool Gateway** with the tenant and user taken from a WorkPilot access token, so kill switches, argument validation, Cedar policies, quotas, bound approvals, idempotency and the audit log all apply exactly as for the agent. Handlers are never called directly and store credentials never reach the client. Tool results are the gateway outcome: ``{"status", "result", "reason", "approval_id"}``. ``needs_approval`` means a human must approve in the WorkPilot inbox; calling the same tool again with the same arguments afterwards executes it (once). Write tools accept ``dry_run=true`` to preview the effect. """ from __future__ import annotations import inspect import uuid from dataclasses import dataclass from typing import Any from mcp.server.mcpserver import MCPServer from mcp.types import ToolAnnotations from core.auth.jwt import decode_token from core.gateway.gateway import Gateway, ToolCall from core.tools.spec import RegisteredTool, RiskTier PACK = "ecommerce" INSTRUCTIONS = ( "Tools for a Pakistani online store (orders, customers, couriers, refunds, customer " "email). Every call is checked by the WorkPilot gateway: some calls return " "status=needs_approval; a human approves them in the WorkPilot inbox, then repeat the " "same call. Use dry_run=true on write tools to preview the effect first. Amounts are " "whole Pakistani rupees." ) @dataclass(frozen=True) class Binding: """Who the MCP session acts as. Derived from a WorkPilot access token, never from args.""" tenant_id: uuid.UUID actor: str # "user:" @classmethod def from_token(cls, token: str) -> Binding: payload = decode_token(token, "access") if not payload.get("tid"): raise PermissionError("token has no tenant") return cls(tenant_id=uuid.UUID(payload["tid"]), actor=f"user:{payload['sub']}") def _tool_fn(gateway: Gateway, binding: Binding, tool: RegisteredTool) -> Any: spec = tool.spec writes = spec.risk_tier >= RiskTier.T1_INTERNAL fields = spec.input_model.model_fields async def call(**kwargs: Any) -> dict[str, Any]: dry_run = bool(kwargs.pop("dry_run", False)) key = kwargs.pop("idempotency_key", None) args = {k: v for k, v in kwargs.items() if k in fields} outcome = await gateway.execute( ToolCall( tenant_id=binding.tenant_id, actor=binding.actor, tool=spec.name, args=args, dry_run=dry_run, idempotency_key=uuid.UUID(key) if key else uuid.uuid4(), ) ) return { "status": outcome.status, "result": outcome.result.model_dump(mode="json") if outcome.result else None, "reason": outcome.reason, "approval_id": str(outcome.approval_id) if outcome.approval_id else None, } # Give the function the input model's signature so MCPServer derives the JSON schema. params = [] for name, f in fields.items(): default = ( inspect.Parameter.empty if f.is_required() else f.get_default(call_default_factory=True) ) params.append( inspect.Parameter( name, inspect.Parameter.KEYWORD_ONLY, default=default, annotation=f.annotation ) ) if writes: params.append( inspect.Parameter( "dry_run", inspect.Parameter.KEYWORD_ONLY, default=False, annotation=bool ) ) params.append( inspect.Parameter( "idempotency_key", inspect.Parameter.KEYWORD_ONLY, default=None, annotation=str | None, ) ) call.__signature__ = inspect.Signature(params, return_annotation=dict[str, Any]) # type: ignore[attr-defined] call.__name__ = spec.name.split(".", 1)[1] call.__doc__ = spec.description return call def build_server(gateway: Gateway, binding: Binding) -> MCPServer: """An MCP server bound to one tenant/user, routing every tool call through ``gateway``.""" server: MCPServer = MCPServer( name="workpilot-shopify-admin", instructions=INSTRUCTIONS, version="0.1.0" ) for spec in gateway.registry.specs(): if spec.pack != PACK: continue tool = gateway.registry.get(spec.name) tier = spec.risk_tier server.add_tool( _tool_fn(gateway, binding, tool), name=spec.name.split(".", 1)[1], description=f"{spec.description} (risk tier T{int(tier)})", annotations=ToolAnnotations( title=spec.name, read_only_hint=tier == RiskTier.T0_READ, destructive_hint=tier >= RiskTier.T2_EXTERNAL, idempotent_hint=tier == RiskTier.T0_READ, open_world_hint=tier >= RiskTier.T2_EXTERNAL, ), structured_output=False, ) return server