Spaces:
Running

File size: 5,392 Bytes
0776bd5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""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:<id>"

    @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