Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

MUL-7812: fix(agent): deliver MCP servers to Pi tasks (#9063)

2penheimer92d0b6666d51
diff --git a/apps/docs/content/docs/providers.fr.mdx b/apps/docs/content/docs/providers.fr.mdx
index 5d6e0dd7b7..02ee2c3980 100644
--- a/apps/docs/content/docs/providers.fr.mdx
+++ b/apps/docs/content/docs/providers.fr.mdx
@@ -36,7 +36,7 @@ Les étapes d'installation se trouvent dans [Installer les outils de codage IA](
| MiniMax Code | `mcode` | — | ✓ | `.minimax/skills/` |
| OpenClaw | `openclaw` | ✓ | ✓ | `skills/` |
| OpenCode | `opencode` | ✓ | ✓ | `.opencode/skills/` |
-| Pi | `pi` | ✓ | — | `.pi/skills/` |
+| Pi | `pi` | ✓ | ✓ | `.pi/skills/` |
| Oh-My-Pi | `omp` | ✓ | ✓ | `.omp/skills/` |
| Qoder CLI | `qodercli` | ✓ | ✓ | `.qoder/skills/` |
| Qoder CN CLI | `qoderclicn` | ✓ | ✓ | `.qoder/skills/` |
@@ -72,7 +72,9 @@ Les règles de relance et de reprise de session se trouvent dans [Exécutions](/
## Configuration MCP
-Antigravity, GitHub Copilot CLI, DevEco Code et Pi ne lisent pas encore la configuration MCP d'un agent ; le champ n'est donc pas affiché lors de la création d'agents pour ces outils.
+Antigravity, GitHub Copilot CLI et DevEco Code ne lisent pas encore la configuration MCP d'un agent ; le champ n'est donc pas affiché lors de la création d'agents pour ces outils.
+
+La transmission d'une configuration MCP gérée à Pi nécessite Pi 0.99.0 ou une version ultérieure. Les versions antérieures de Pi continuent d'exécuter les agents sans configuration MCP.
<Callout type="warning">
Les commandes, arguments et variables d'environnement des serveurs MCP sont enregistrés côté serveur avec la configuration de l'agent. N'écrivez pas dans la configuration des identifiants locaux que vous n'avez pas besoin de partager.
diff --git a/apps/docs/content/docs/providers.ja.mdx b/apps/docs/content/docs/providers.ja.mdx
index 4fa97d0b67..54522e9521 100644
--- a/apps/docs/content/docs/providers.ja.mdx
+++ b/apps/docs/content/docs/providers.ja.mdx
@@ -36,7 +36,7 @@ Multica は、普段使っている AI コーディングツールの代わり
| MiniMax Code | `mcode` | — | ✓ | `.minimax/skills/` |
| OpenClaw | `openclaw` | ✓ | ✓ | `skills/` |
| OpenCode | `opencode` | ✓ | ✓ | `.opencode/skills/` |
-| Pi | `pi` | ✓ | — | `.pi/skills/` |
+| Pi | `pi` | ✓ | ✓ | `.pi/skills/` |
| Oh-My-Pi | `omp` | ✓ | ✓ | `.omp/skills/` |
| Qoder CLI | `qodercli` | ✓ | ✓ | `.qoder/skills/` |
| Qoder CN CLI | `qoderclicn` | ✓ | ✓ | `.qoder/skills/` |
@@ -72,7 +72,9 @@ Multica はツールから返されたセッション識別子を保存します
## MCP 設定
-Antigravity、GitHub Copilot CLI、DevEco Code、Pi は、現時点ではエージェントの MCP 設定を読み取りません。そのため、これらのツールを選んだ場合、エージェント作成画面にこの項目は表示されません。
+Antigravity、GitHub Copilot CLI、DevEco Code は、現時点ではエージェントの MCP 設定を読み取りません。そのため、これらのツールを選んだ場合、エージェント作成画面にこの項目は表示されません。
+
+Pi への管理 MCP 設定の引き渡しには Pi 0.99.0 以降が必要です。それより古い Pi でも、MCP 設定のないエージェントは引き続き実行できます。
<Callout type="warning">
MCP server のコマンド、引数、環境変数は、エージェント設定の一部としてサーバーに保存されます。共有する必要がないローカルの認証情報を設定へ直接入力しないでください。
diff --git a/apps/docs/content/docs/providers.ko.mdx b/apps/docs/content/docs/providers.ko.mdx
index 188e53ce70..6ddb09ef51 100644
--- a/apps/docs/content/docs/providers.ko.mdx
+++ b/apps/docs/content/docs/providers.ko.mdx
@@ -36,7 +36,7 @@ Multica는 사용 중인 AI 코딩 도구를 대체하지 않습니다. 런타
| MiniMax Code | `mcode` | — | ✓ | `.minimax/skills/` |
| OpenClaw | `openclaw` | ✓ | ✓ | `skills/` |
| OpenCode | `opencode` | ✓ | ✓ | `.opencode/skills/` |
-| Pi | `pi` | ✓ | — | `.pi/skills/` |
+| Pi | `pi` | ✓ | ✓ | `.pi/skills/` |
| Oh-My-Pi | `omp` | ✓ | ✓ | `.omp/skills/` |
| Qoder CLI | `qodercli` | ✓ | ✓ | `.qoder/skills/` |
| Qoder CN CLI | `qoderclicn` | ✓ | ✓ | `.qoder/skills/` |
@@ -72,7 +72,9 @@ Multica는 도구가 반환한 세션 식별자를 저장합니다. 다음에
## MCP 설정
-Antigravity, GitHub Copilot CLI, DevEco Code, Pi는 현재 에이전트의 MCP 설정을 읽지 않으므로 에이전트를 만들 때 이 항목이 표시되지 않습니다.
+Antigravity, GitHub Copilot CLI, DevEco Code는 현재 에이전트의 MCP 설정을 읽지 않으므로 에이전트를 만들 때 이 항목이 표시되지 않습니다.
+
+Pi에 관리형 MCP 설정을 전달하려면 Pi 0.99.0 이상이 필요합니다. 이전 Pi 버전에서도 MCP 설정이 없는 에이전트는 계속 실행할 수 있습니다.
<Callout type="warning">
MCP server의 명령, 인수, 환경 변수는 에이전트 설정과 함께 서버에 저장됩니다. 공유할 필요가 없는 로컬 자격 증명을 설정에 직접 넣지 마세요.
diff --git a/apps/docs/content/docs/providers.mdx b/apps/docs/content/docs/providers.mdx
index 43363e2769..1e93670dee 100644
--- a/apps/docs/content/docs/providers.mdx
+++ b/apps/docs/content/docs/providers.mdx
@@ -36,7 +36,7 @@ Install steps are in [Install AI coding tools](/install-agent-runtime).
| MiniMax Code | `mcode` | — | ✓ | `.minimax/skills/` |
| OpenClaw | `openclaw` | ✓ | ✓ | `skills/` |
| OpenCode | `opencode` | ✓ | ✓ | `.opencode/skills/` |
-| Pi | `pi` | ✓ | — | `.pi/skills/` |
+| Pi | `pi` | ✓ | ✓ | `.pi/skills/` |
| Oh-My-Pi | `omp` | ✓ | ✓ | `.omp/skills/` |
| Qoder CLI | `qodercli` | ✓ | ✓ | `.qoder/skills/` |
| Qoder CN CLI | `qoderclicn` | ✓ | ✓ | `.qoder/skills/` |
@@ -72,7 +72,9 @@ Retry and session-resumption rules are in [Runs](/tasks#manual-retry).
## MCP configuration
-Antigravity, GitHub Copilot CLI, DevEco Code, and Pi do not read the MCP configuration on an agent yet, so the field is not shown when creating agents for them.
+Antigravity, GitHub Copilot CLI, and DevEco Code do not read the MCP configuration on an agent yet, so the field is not shown when creating agents for them.
+
+Managed MCP delivery for Pi requires Pi 0.99.0 or later. Older Pi versions continue to run agents that have no MCP configuration.
<Callout type="warning">
MCP server commands, arguments, and environment variables are saved server-side with the agent configuration. Do not write local credentials you have no need to share into the configuration.
diff --git a/apps/docs/content/docs/providers.zh.mdx b/apps/docs/content/docs/providers.zh.mdx
index b89cfe15d0..0587ad72dc 100644
--- a/apps/docs/content/docs/providers.zh.mdx
+++ b/apps/docs/content/docs/providers.zh.mdx
@@ -36,7 +36,7 @@ Multica 不会替代你使用的 AI 编程工具。运行时会调用电脑上
| MiniMax Code | `mcode` | — | ✓ | `.minimax/skills/` |
| OpenClaw | `openclaw` | ✓ | ✓ | `skills/` |
| OpenCode | `opencode` | ✓ | ✓ | `.opencode/skills/` |
-| Pi | `pi` | ✓ | — | `.pi/skills/` |
+| Pi | `pi` | ✓ | ✓ | `.pi/skills/` |
| Oh-My-Pi | `omp` | ✓ | ✓ | `.omp/skills/` |
| Qoder CLI | `qodercli` | ✓ | ✓ | `.qoder/skills/` |
| Qoder CN CLI | `qoderclicn` | ✓ | ✓ | `.qoder/skills/` |
@@ -72,7 +72,9 @@ Multica 会保存工具返回的会话标识。下一次在同一任务中继续
## MCP 配置
-Antigravity、GitHub Copilot CLI、DevEco Code 和 Pi 暂不读取智能体中的 MCP 配置,因此创建智能体时不会显示这一项。
+Antigravity、GitHub Copilot CLI 和 DevEco Code 暂不读取智能体中的 MCP 配置,因此创建智能体时不会显示这一项。
+
+向 Pi 下发受管 MCP 配置需要 Pi 0.99.0 或更高版本。旧版 Pi 仍可运行未配置 MCP 的智能体。
<Callout type="warning">
MCP server 的命令、参数和环境变量会随智能体配置保存在服务器端。不要把不需要共享的本地凭据直接写入配置。
diff --git a/packages/core/agents/mcp-support.test.ts b/packages/core/agents/mcp-support.test.ts
index 674876b02c..24e180f7b0 100644
--- a/packages/core/agents/mcp-support.test.ts
+++ b/packages/core/agents/mcp-support.test.ts
@@ -9,10 +9,7 @@ describe("providerSupportsMcpConfig", () => {
it("rejects providers whose runtime ignores mcp_config", () => {
expect(providerSupportsMcpConfig("antigravity")).toBe(false);
expect(providerSupportsMcpConfig("copilot")).toBe(false);
- // Pi ships without MCP by design: upstream's README states "No MCP." and
- // directs users to extensions instead, so there is no config file Multica
- // could write that pi would read. Only its omp fork consumes mcp_config.
- expect(providerSupportsMcpConfig("pi")).toBe(false);
+ expect(providerSupportsMcpConfig("pi")).toBe(true);
// ZeroClaw's ACP server never reads `params.mcpServers` — MCP lives in
// ZeroClaw's own config-dir, so a value saved here could not be honoured.
expect(providerSupportsMcpConfig("zeroclaw")).toBe(false);
diff --git a/packages/core/agents/mcp-support.ts b/packages/core/agents/mcp-support.ts
index 67bbf2e1bc..d1e150fb78 100644
--- a/packages/core/agents/mcp-support.ts
+++ b/packages/core/agents/mcp-support.ts
@@ -19,6 +19,7 @@ const MCP_SUPPORTED_PROVIDERS = new Set([
"kiro",
"opencode",
"openclaw",
+ "pi",
"qoder",
"qoderclicn",
"qwen",
diff --git a/server/internal/daemon/execenv/pi_mcp_real_integration_test.go b/server/internal/daemon/execenv/pi_mcp_real_integration_test.go
new file mode 100644
index 0000000000..14b74941f1
--- /dev/null
+++ b/server/internal/daemon/execenv/pi_mcp_real_integration_test.go
@@ -0,0 +1,359 @@
+//go:build agentintegration
+
+package execenv
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "log/slog"
+ "net"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "runtime"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/multica-ai/multica/server/pkg/agent"
+)
+
+// Real-CLI acceptance for Pi MCP delivery. Opt-in twice: the agentintegration
+// build tag, and MULTICA_RUN_REAL_AGENT_SMOKE, because this executes the pi
+// binary installed on the host. HOME points at a temp directory so the test
+// does not read or write the user's ~/.pi. Pi exits before connecting MCP
+// when the temp home has no model credential, so the fixture points --model
+// at a local listener that accepts the request and never returns a completion.
+// That is not the user's account. The oracles are a local stdio program that
+// records its own start and a local Streamable HTTP server that records Pi's
+// initialize request.
+func TestPiMcpUntrustedProjectDoesNotStartServer(t *testing.T) {
+ bin, workDir, sentinel, raw := piMcpFixture(t)
+ writePiProjectMcp(t, workDir, raw)
+
+ sessionPath := filepath.Join(workDir, "session.jsonl")
+ if err := os.WriteFile(sessionPath, nil, 0o644); err != nil {
+ t.Fatal(err)
+ }
+ // The stub model never completes, so this context is what ends the process.
+ // The wait is longer than the extension test needs to observe a start.
+ ctx, cancel := context.WithTimeout(context.Background(), 12*time.Second)
+ defer cancel()
+ cmd := exec.CommandContext(ctx, bin,
+ "-p", "--mode", "json", "--offline",
+ "--session", sessionPath,
+ "--model", piMcpStubModel,
+ )
+ cmd.Dir = workDir
+ cmd.Env = os.Environ()
+ cmd.Stdin = strings.NewReader("ping\n")
+ var output strings.Builder
+ cmd.Stdout = &output
+ cmd.Stderr = &output
+ if err := cmd.Start(); err != nil {
+ t.Fatalf("start untrusted pi: %v", err)
+ }
+ done := make(chan struct{})
+ go func() {
+ _ = cmd.Wait()
+ close(done)
+ }()
+
+ deadline := time.Now().Add(8 * time.Second)
+ for time.Now().Before(deadline) {
+ if started, readErr := os.ReadFile(sentinel); readErr == nil {
+ t.Fatalf("untrusted pi started the MCP server (%q); output:\n%s", started, output.String())
+ }
+ select {
+ case <-done:
+ if started, readErr := os.ReadFile(sentinel); readErr == nil {
+ t.Fatalf("untrusted pi started the MCP server (%q); output:\n%s", started, output.String())
+ }
+ if strings.Contains(output.String(), "No API key") {
+ t.Fatalf("untrusted pi exited before project trust was tested:\n%s", output.String())
+ }
+ return
+ case <-time.After(100 * time.Millisecond):
+ }
+ }
+ cancel()
+ <-done
+}
+
+func TestPiMcpExtensionLaunchStartsServer(t *testing.T) {
+ bin, workDir, sentinel, raw := piMcpFixture(t)
+ httpURL, httpInitialized := piHTTPMCPProbe(t)
+ var config struct {
+ McpServers map[string]any `json:"mcpServers"`
+ }
+ if err := json.Unmarshal(raw, &config); err != nil {
+ t.Fatal(err)
+ }
+ config.McpServers["remote-probe"] = map[string]any{
+ "type": "http",
+ "url": httpURL,
+ }
+ raw, err := json.Marshal(config)
+ if err != nil {
+ t.Fatal(err)
+ }
+ extensionTmp := t.TempDir()
+ t.Setenv("TMPDIR", extensionTmp)
+
+ var logBuf bytes.Buffer
+ logger := slog.New(slog.NewTextHandler(&logBuf, nil))
+ ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
+ defer cancel()
+ backend, err := agent.New("pi", agent.Config{
+ ExecutablePath: bin,
+ CLIVersion: "1.0.2",
+ BuiltinRuntime: true,
+ Logger: logger,
+ })
+ if err != nil {
+ t.Fatalf("new pi backend: %v", err)
+ }
+ session, err := backend.Execute(ctx, "ping", agent.ExecOptions{
+ Cwd: workDir,
+ Model: piMcpStubModel,
+ CustomArgs: []string{"--offline"},
+ McpConfig: raw,
+ })
+ if err != nil {
+ t.Fatalf("execute pi: %v", err)
+ }
+ resultCh := make(chan agent.Result, 1)
+ go func() {
+ for range session.Messages {
+ }
+ result, ok := <-session.Result
+ if ok {
+ resultCh <- result
+ }
+ }()
+
+ logged := logBuf.String()
+ if strings.Contains(logged, "--approve") {
+ t.Fatalf("launch args include --approve:\n%s", logged)
+ }
+ if !strings.Contains(logged, "--extension") {
+ t.Fatalf("launch args missing --extension:\n%s", logged)
+ }
+ if _, err := os.Stat(filepath.Join(workDir, ".pi", "mcp.json")); !os.IsNotExist(err) {
+ t.Fatalf("Execute created .pi/mcp.json, stat error = %v", err)
+ }
+
+ deadline := time.Now().Add(25 * time.Second)
+ stdioStarted := false
+ httpStarted := false
+ for time.Now().Before(deadline) && (!stdioStarted || !httpStarted) {
+ if data, readErr := os.ReadFile(sentinel); readErr == nil && strings.TrimSpace(string(data)) == "started" {
+ stdioStarted = true
+ }
+ select {
+ case <-httpInitialized:
+ httpStarted = true
+ case result := <-resultCh:
+ t.Fatalf("pi exited before starting both MCP servers: status=%s error=%s output=%s", result.Status, result.Error, result.Output)
+ case <-time.After(100 * time.Millisecond):
+ }
+ }
+ if !stdioStarted || !httpStarted {
+ t.Fatalf("pi extension starts: stdio=%v http=%v", stdioStarted, httpStarted)
+ }
+ cancel()
+ select {
+ case <-resultCh:
+ case <-time.After(15 * time.Second):
+ t.Fatal("pi did not exit after cancel")
+ }
+
+ cleanupDeadline := time.Now().Add(2 * time.Second)
+ for {
+ matches, globErr := filepath.Glob(filepath.Join(extensionTmp, piMcpExtensionGlob))
+ if globErr != nil {
+ t.Fatal(globErr)
+ }
+ if len(matches) == 0 {
+ return
+ }
+ if time.Now().After(cleanupDeadline) {
+ t.Fatalf("temporary pi extension still present: %v", matches)
+ }
+ time.Sleep(20 * time.Millisecond)
+ }
+}
+
+func piHTTPMCPProbe(t *testing.T) (string, <-chan struct{}) {
+ t.Helper()
+ initialized := make(chan struct{})
+ var once sync.Once
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodPost {
+ w.WriteHeader(http.StatusMethodNotAllowed)
+ return
+ }
+ var request struct {
+ JSONRPC string `json:"jsonrpc"`
+ ID json.RawMessage `json:"id,omitempty"`
+ Method string `json:"method"`
+ }
+ if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
+ w.WriteHeader(http.StatusBadRequest)
+ return
+ }
+ if request.Method == "notifications/initialized" {
+ w.WriteHeader(http.StatusAccepted)
+ return
+ }
+ var result any
+ switch request.Method {
+ case "initialize":
+ once.Do(func() { close(initialized) })
+ result = map[string]any{
+ "protocolVersion": "2024-11-05",
+ "capabilities": map[string]any{"tools": map[string]any{}},
+ "serverInfo": map[string]any{"name": "pi-http-probe", "version": "1"},
+ }
+ case "tools/list":
+ result = map[string]any{"tools": []any{}}
+ default:
+ w.Header().Set("Content-Type", "application/json")
+ _ = json.NewEncoder(w).Encode(map[string]any{
+ "jsonrpc": "2.0",
+ "id": request.ID,
+ "error": map[string]any{"code": -32601, "message": "method not found"},
+ })
+ return
+ }
+ w.Header().Set("Content-Type", "application/json")
+ _ = json.NewEncoder(w).Encode(map[string]any{
+ "jsonrpc": "2.0",
+ "id": request.ID,
+ "result": result,
+ })
+ }))
+ t.Cleanup(server.Close)
+ return server.URL + "/mcp", initialized
+}
+
+const piMcpExtensionGlob = "multica-pi-mcp-*"
+
+func piMcpFixture(t *testing.T) (bin, workDir, sentinel string, raw json.RawMessage) {
+ t.Helper()
+ if os.Getenv("MULTICA_RUN_REAL_AGENT_SMOKE") != "1" {
+ t.Skip("set MULTICA_RUN_REAL_AGENT_SMOKE=1 to allow real agent CLI access")
+ }
+ if testing.Short() {
+ t.Skip("skipping real-binary smoke test in -short mode")
+ }
+ if runtime.GOOS == "windows" {
+ t.Skip("shell-script MCP fixture is POSIX-only")
+ }
+
+ var err error
+ bin, err = exec.LookPath("pi")
+ if err != nil {
+ t.Skip("pi not on PATH; skipping real-binary smoke test")
+ }
+ if version, verErr := exec.Command(bin, "--version").CombinedOutput(); verErr == nil {
+ t.Logf("pi CLI version: %s", strings.TrimSpace(string(version)))
+ }
+
+ home := t.TempDir()
+ t.Setenv("HOME", home)
+ t.Setenv("USERPROFILE", home)
+ writePiStubModel(t, home)
+
+ workDir = t.TempDir()
+ sentinel = filepath.Join(workDir, "probe.log")
+ probe := filepath.Join(workDir, "probe.sh")
+ script := "#!/bin/sh\nprintf 'started\\n' >> \"$PI_MCP_PROBE_LOG\"\nsleep 30\n"
+ if err := os.WriteFile(probe, []byte(script), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ raw, err = json.Marshal(map[string]any{
+ "mcpServers": map[string]any{
+ "probe": map[string]any{
+ "command": probe,
+ "env": map[string]string{"PI_MCP_PROBE_LOG": sentinel},
+ },
+ },
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ return bin, workDir, sentinel, raw
+}
+
+func writePiProjectMcp(t *testing.T, workDir string, raw []byte) {
+ t.Helper()
+ path := filepath.Join(workDir, ".pi", "mcp.json")
+ if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(path, raw, 0o600); err != nil {
+ t.Fatal(err)
+ }
+}
+
+const piMcpStubModel = "localstub/stub"
+
+// writePiStubModel registers a provider that speaks to a listener on
+// 127.0.0.1. The listener accepts one request and then holds the connection,
+// so Pi gets past its API-key check without calling a hosted model.
+func writePiStubModel(t *testing.T, home string) {
+ t.Helper()
+ ln, err := net.Listen("tcp", "127.0.0.1:0")
+ if err != nil {
+ t.Fatal(err)
+ }
+ hold, stop := context.WithCancel(context.Background())
+ t.Cleanup(func() {
+ stop()
+ _ = ln.Close()
+ })
+ go func() {
+ for {
+ conn, acceptErr := ln.Accept()
+ if acceptErr != nil {
+ return
+ }
+ go func(c net.Conn) {
+ defer c.Close()
+ buf := make([]byte, 4096)
+ _, _ = c.Read(buf)
+ <-hold.Done()
+ }(conn)
+ }
+ }()
+
+ dir := filepath.Join(home, ".pi", "agent")
+ if err := os.MkdirAll(dir, 0o700); err != nil {
+ t.Fatal(err)
+ }
+ raw, err := json.Marshal(map[string]any{
+ "providers": map[string]any{
+ "localstub": map[string]any{
+ "baseUrl": "http://" + ln.Addr().String() + "/v1",
+ "api": "openai-completions",
+ "apiKey": "local-stub",
+ "models": []any{map[string]any{
+ "id": "stub",
+ "contextWindow": 8000,
+ "maxTokens": 256,
+ }},
+ },
+ },
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(dir, "models.json"), raw, 0o600); err != nil {
+ t.Fatal(err)
+ }
+}
diff --git a/server/internal/daemon/execenv/pi_mcp_test.go b/server/internal/daemon/execenv/pi_mcp_test.go
new file mode 100644
index 0000000000..8f1a8caecb
--- /dev/null
+++ b/server/internal/daemon/execenv/pi_mcp_test.go
@@ -0,0 +1,72 @@
+package execenv
+
+import (
+ "encoding/json"
+ "os"
+ "path/filepath"
+ "testing"
+)
+
+func TestPreparePiLeavesProjectMcpConfigAlone(t *testing.T) {
+ t.Parallel()
+ workspacesRoot := t.TempDir()
+
+ env, err := Prepare(PrepareParams{
+ WorkspacesRoot: workspacesRoot,
+ WorkspaceID: "ws-pi-mcp",
+ TaskID: "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
+ AgentName: "Pi",
+ Provider: "pi",
+ McpConfig: json.RawMessage(`{"mcpServers":{"probe":{"command":"echo"}}}`),
+ Task: TaskContextForEnv{
+ IssueID: "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
+ },
+ }, testLogger())
+ if err != nil {
+ t.Fatalf("Prepare: %v", err)
+ }
+ defer env.Cleanup(true)
+
+ if _, err := os.Stat(filepath.Join(env.WorkDir, ".pi", "mcp.json")); !os.IsNotExist(err) {
+ t.Fatalf("Prepare created .pi/mcp.json, stat error = %v", err)
+ }
+}
+
+func TestPreparePiDoesNotOverwriteExistingProjectMcpConfig(t *testing.T) {
+ t.Parallel()
+ workspacesRoot := t.TempDir()
+ userDir := t.TempDir()
+ path := filepath.Join(userDir, ".pi", "mcp.json")
+ if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ existing := []byte(`{"mcpServers":{"user":{"command":"echo"}}}`)
+ if err := os.WriteFile(path, existing, 0o644); err != nil {
+ t.Fatal(err)
+ }
+
+ env, err := Prepare(PrepareParams{
+ WorkspacesRoot: workspacesRoot,
+ WorkspaceID: "ws-pi-mcp-existing",
+ TaskID: "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
+ AgentName: "Pi",
+ Provider: "pi",
+ LocalWorkDir: userDir,
+ McpConfig: json.RawMessage(`{"mcpServers":{"managed":{"command":"echo"}}}`),
+ Task: TaskContextForEnv{
+ IssueID: "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
+ },
+ }, testLogger())
+ if err != nil {
+ t.Fatalf("Prepare: %v", err)
+ }
+ defer env.Cleanup(true)
+
+ data, err := os.ReadFile(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if string(data) != string(existing) {
+ t.Fatalf("existing .pi/mcp.json changed to %s", data)
+ }
+}
diff --git a/server/internal/daemon/runtime_mcp.go b/server/internal/daemon/runtime_mcp.go
index 4bb5765ee6..41aefae0d8 100644
--- a/server/internal/daemon/runtime_mcp.go
+++ b/server/internal/daemon/runtime_mcp.go
@@ -302,6 +302,9 @@ func loadRuntimeMcpServerConfigs(provider string) (map[string]any, bool, error)
}
key, format = "mcp.servers", "json"
default:
+ // pi is intentionally absent. The CLI reads ~/.pi/agent/mcp.json on its
+ // own, and a project .pi/mcp.json replaces entries with the same name.
+ // Copying the user file into the task file would start those servers twice.
return map[string]any{}, false, nil
}
@@ -435,6 +438,10 @@ func listRuntimeLocalMcpServers(provider string) ([]runtimeLocalMcpServerSummary
path = filepath.Join(stateDir, "openclaw.json")
}
key, source, format = "mcp.servers", "User config", "json"
+ case "pi":
+ // Inventory only, same as omp. Pi already loads this file at startup,
+ // so loadRuntimeMcpServerConfigs must not merge it into the task.
+ path, key, source, format = filepath.Join(home, ".pi", "agent", "mcp.json"), "mcpServers", "User config", "json"
case "omp":
// Inventory scope: omp discovers servers from a multi-level precedence
// chain (.omp/mcp.json, .omp/.mcp.json, profile/user-level configs, and
diff --git a/server/internal/daemon/runtime_mcp_test.go b/server/internal/daemon/runtime_mcp_test.go
index 3eff173acb..2daab8cd39 100644
--- a/server/internal/daemon/runtime_mcp_test.go
+++ b/server/internal/daemon/runtime_mcp_test.go
@@ -113,6 +113,59 @@ func TestListRuntimeLocalMcpServersUnknownProvider(t *testing.T) {
}
}
+func TestListRuntimeLocalMcpServersPi(t *testing.T) {
+ home := t.TempDir()
+ t.Setenv("HOME", home)
+ configDir := filepath.Join(home, ".pi", "agent")
+ if err := os.MkdirAll(configDir, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ config := `{"mcpServers":{"native":{"command":"native-server","enabled":false}}}`
+ if err := os.WriteFile(filepath.Join(configDir, "mcp.json"), []byte(config), 0o600); err != nil {
+ t.Fatal(err)
+ }
+
+ servers, supported, err := listRuntimeLocalMcpServers("pi")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !supported || len(servers) != 1 {
+ t.Fatalf("supported=%v servers=%#v", supported, servers)
+ }
+ if servers[0].Name != "native" || servers[0].Transport != "stdio" || servers[0].Enabled {
+ t.Fatalf("native summary = %#v", servers[0])
+ }
+}
+
+func TestMergeRuntimeAndAgentMcpConfigPiLeavesUserFileAlone(t *testing.T) {
+ home := t.TempDir()
+ t.Setenv("HOME", home)
+ configDir := filepath.Join(home, ".pi", "agent")
+ if err := os.MkdirAll(configDir, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(configDir, "mcp.json"), []byte(`{"mcpServers":{"runtime-only":{"command":"runtime-server"}}}`), 0o600); err != nil {
+ t.Fatal(err)
+ }
+
+ merged, err := mergeRuntimeAndAgentMcpConfig("pi", json.RawMessage(`{"mcpServers":{"agent":{"command":"agent-server"}}}`))
+ if err != nil {
+ t.Fatal(err)
+ }
+ var document struct {
+ McpServers map[string]map[string]any `json:"mcpServers"`
+ }
+ if err := json.Unmarshal(merged, &document); err != nil {
+ t.Fatal(err)
+ }
+ if _, ok := document.McpServers["runtime-only"]; ok {
+ t.Fatalf("user server was copied into the task config: %#v", document.McpServers)
+ }
+ if document.McpServers["agent"]["command"] != "agent-server" {
+ t.Fatalf("merged servers = %#v", document.McpServers)
+ }
+}
+
func TestMergeRuntimeAndAgentMcpConfigOmpUsesAgentConfig(t *testing.T) {
redirectTestHome(t, t.TempDir())
merged, err := mergeRuntimeAndAgentMcpConfig("omp", json.RawMessage(`{"mcpServers":{"agent":{"command":"agent-server"}}}`))
diff --git a/server/pkg/agent/agent.go b/server/pkg/agent/agent.go
index 5545440c3e..1352d8a6c5 100644
--- a/server/pkg/agent/agent.go
+++ b/server/pkg/agent/agent.go
@@ -133,6 +133,9 @@ type ExecOptions struct {
// through Claude Code's --settings flag. It currently carries restrictive
// runtime-skill overrides only; other providers ignore it.
ClaudeSettingsPath string
+ // piMcpExtensionPath is set by piBackend.Execute after it writes the
+ // temporary MCP extension. The daemon does not fill it.
+ piMcpExtensionPath string
}
// runContext derives the execution context for an agent subprocess from the
diff --git a/server/pkg/agent/pi.go b/server/pkg/agent/pi.go
index 4c00924d33..ac2c880d87 100644
--- a/server/pkg/agent/pi.go
+++ b/server/pkg/agent/pi.go
@@ -416,6 +416,24 @@ func (b *piBackend) Execute(ctx context.Context, prompt string, opts ExecOptions
}
}
+ extensionPath, err := b.preparePiMcpExtension(opts.McpConfig)
+ if err != nil {
+ releasePiSessionFileLock(sessionLock)
+ return nil, fmt.Errorf("%s mcp extension: %w", label, err)
+ }
+ // Execute owns the temp extension until the process is running. The
+ // reader goroutine takes ownership after start so a launch failure still
+ // deletes the directory, and a running process can read it until exit.
+ releaseExtension := func() { removePiMcpExtension(extensionPath) }
+ defer func() {
+ if releaseExtension != nil {
+ releaseExtension()
+ }
+ }()
+ if extensionPath != "" {
+ opts.piMcpExtensionPath = extensionPath
+ }
+
runCtx, cancel := runContext(ctx, timeout)
processCtx, cancelProcess := context.WithCancel(runCtx)
@@ -528,7 +546,9 @@ func (b *piBackend) Execute(ctx context.Context, prompt string, opts ExecOptions
closePiReadPipe(stderrRead)
}()
+ releaseExtension = nil
go func() {
+ defer removePiMcpExtension(extensionPath)
defer func() { releasePiSessionFileLock(sessionLock) }()
defer cancelProcess()
defer cancel()
@@ -1112,9 +1132,141 @@ func buildPiArgs(sessionPath string, opts ExecOptions, logger *slog.Logger) []st
// inlining the same runtime brief would duplicate it on every turn.
// Verified against Pi 0.67.2 (MUL-5392).
args = append(args, filterPiCustomArgs(opts.CustomArgs, logger)...)
+ // The extension is explicit, so Pi loads it without trusting the project.
+ // It stays after custom args so the managed path cannot be mistaken for the
+ // value of an extension-defined flag. A user-provided --approve remains
+ // independent and continues to opt into all project-local Pi resources.
+ if opts.piMcpExtensionPath != "" {
+ args = append(args, "--extension", opts.piMcpExtensionPath)
+ }
return args
}
+const (
+ piMcpExtensionDirPrefix = "multica-pi-mcp-"
+ // Pi 0.99.0 introduced the built-in MCP extension and the
+ // registerMcpServer API used by the task-local adapter below. This is a
+ // capability floor, not a global Pi floor: older Pi installations keep
+ // working for agents without managed MCP configuration.
+ piMcpMinVersion = "0.99.0"
+)
+
+// preparePiMcpExtension writes Pi's own temporary extension. omp shares this
+// backend but keeps its project mcp.json, so it never gets this file.
+func (b *piBackend) preparePiMcpExtension(raw json.RawMessage) (string, error) {
+ if b.providerLabel == "omp" || !hasManagedMcpConfig(raw) {
+ return "", nil
+ }
+ servers, err := piMcpExtensionServers(raw)
+ if err != nil {
+ return "", err
+ }
+ if len(servers) == 0 {
+ return "", nil
+ }
+ if err := b.validatePiMcpVersion(); err != nil {
+ return "", err
+ }
+ return writePiMcpExtension(raw)
+}
+
+func (b *piBackend) validatePiMcpVersion() error {
+ // Custom runtime profiles only promise Pi's JSON protocol, not the vendor's
+ // version scheme. Their explicit extension load remains the capability
+ // probe; applying Pi's vendor floor would reject compatible wrappers.
+ if !b.cfg.BuiltinRuntime {
+ return nil
+ }
+ detected, err := parseSemver(b.cfg.CLIVersion)
+ if err != nil {
+ return fmt.Errorf("pi MCP requires a newer version: %s or later; could not verify detected version %q; upgrade Pi or remove the MCP configuration", piMcpMinVersion, b.cfg.CLIVersion)
+ }
+ minimum, _ := parseSemver(piMcpMinVersion)
+ if detected.lessThan(minimum) {
+ return fmt.Errorf("pi MCP requires a newer version: %s or later (detected %s); upgrade Pi or remove the MCP configuration", piMcpMinVersion, b.cfg.CLIVersion)
+ }
+ return nil
+}
+
+// writePiMcpExtension writes mcp-extension.mjs under a multica-pi-mcp-*
+// directory. An empty server list returns an empty path and leaves no
+// directory behind. The caller deletes the directory with
+// removePiMcpExtension. Pi validates each server; the generated extension
+// isolates those errors so one malformed entry cannot suppress valid servers.
+func writePiMcpExtension(raw json.RawMessage) (string, error) {
+ if !hasManagedMcpConfig(raw) {
+ return "", nil
+ }
+ servers, err := piMcpExtensionServers(raw)
+ if err != nil {
+ return "", err
+ }
+ if len(servers) == 0 {
+ return "", nil
+ }
+ encoded, err := json.Marshal(servers)
+ if err != nil {
+ return "", err
+ }
+ literal, err := json.Marshal(string(encoded))
+ if err != nil {
+ return "", err
+ }
+ script := "const servers = JSON.parse(" + string(literal) + ");\n" +
+ "export default function (pi) {\n" +
+ " if (typeof pi.registerMcpServer !== \"function\") {\n" +
+ " throw new Error(\"Multica MCP delivery requires Pi " + piMcpMinVersion + " or newer\");\n" +
+ " }\n" +
+ " for (const [name, config] of Object.entries(servers)) {\n" +
+ " try {\n" +
+ " pi.registerMcpServer(name, config);\n" +
+ " } catch (error) {\n" +
+ " const reason = error instanceof Error ? error.message : String(error);\n" +
+ " console.error(\"[multica] could not register MCP server \" + JSON.stringify(name) + \": \" + reason);\n" +
+ " }\n" +
+ " }\n" +
+ "}\n"
+ dir, err := os.MkdirTemp("", piMcpExtensionDirPrefix)
+ if err != nil {
+ return "", err
+ }
+ path := filepath.Join(dir, "mcp-extension.mjs")
+ if err := os.WriteFile(path, []byte(script), 0o600); err != nil {
+ removePiMcpExtension(path)
+ return "", err
+ }
+ return path, nil
+}
+
+// removePiMcpExtension deletes the temporary extension directory. It refuses
+// any path whose parent is not a multica-pi-mcp-* directory.
+func removePiMcpExtension(path string) {
+ if path == "" {
+ return
+ }
+ dir := filepath.Dir(path)
+ if !strings.HasPrefix(filepath.Base(dir), piMcpExtensionDirPrefix) {
+ return
+ }
+ _ = os.RemoveAll(dir)
+}
+
+func piMcpExtensionServers(raw json.RawMessage) (map[string]json.RawMessage, error) {
+ var doc map[string]json.RawMessage
+ if err := json.Unmarshal(raw, &doc); err != nil {
+ return nil, fmt.Errorf("parse mcp_config: %w", err)
+ }
+ rawServers, ok := doc["mcpServers"]
+ if !ok || bytes.Equal(bytes.TrimSpace(rawServers), []byte("null")) {
+ return nil, nil
+ }
+ var servers map[string]json.RawMessage
+ if err := json.Unmarshal(rawServers, &servers); err != nil {
+ return nil, fmt.Errorf("parse mcp_config mcpServers: %w", err)
+ }
+ return servers, nil
+}
+
// filterPiCustomArgs removes @file and positional message inputs from
// custom_args. Once the task prompt is delivered on stdin, Pi concatenates the
// first positional message to stdin with no separator. Keeping those tokens
diff --git a/server/pkg/agent/pi_test.go b/server/pkg/agent/pi_test.go
index ea395c8743..f0df99720a 100644
--- a/server/pkg/agent/pi_test.go
+++ b/server/pkg/agent/pi_test.go
@@ -2,6 +2,7 @@ package agent
import (
"context"
+ "encoding/json"
"fmt"
"log/slog"
"os"
@@ -36,6 +37,12 @@ func TestBuildPiArgsBasicFlags(t *testing.T) {
t.Errorf("expected %q in args, got: %v", want, args)
}
}
+ if got := countArg(args, "--approve"); got != 0 {
+ t.Errorf("--approve count = %d, want 0 in %v", got, args)
+ }
+ if countArg(args, "--extension") != 0 {
+ t.Errorf("extension flag without a managed config: %v", args)
+ }
for _, arg := range args {
if arg == "hello world" {
@@ -47,6 +54,46 @@ func TestBuildPiArgsBasicFlags(t *testing.T) {
// Pi reads the per-task AGENTS.md the daemon writes into the workdir, so the
// daemon never populates SystemPrompt for it (providerNeedsInlineSystemPrompt).
// Forwarding it anyway would duplicate the whole runtime brief on every turn.
+func TestBuildPiArgsPreservesProjectTrustFlags(t *testing.T) {
+ args := buildPiArgs("/tmp/s.jsonl", ExecOptions{
+ CustomArgs: []string{"--no-approve", "-a", "--approve", "-na", "--offline"},
+ }, slog.Default())
+
+ for _, kept := range []string{"--no-approve", "-a", "--approve", "-na", "--offline"} {
+ if countArg(args, kept) != 1 {
+ t.Errorf("custom %s missing from %v", kept, args)
+ }
+ }
+}
+
+func TestBuildPiArgsAppendsMcpExtension(t *testing.T) {
+ extensionPath := "/tmp/multica-pi-mcp-test/mcp-extension.mjs"
+ args := buildPiArgs("/tmp/s.jsonl", ExecOptions{
+ CustomArgs: []string{"--offline", "--approve"},
+ piMcpExtensionPath: extensionPath,
+ }, slog.Default())
+
+ if countArg(args, "--approve") != 1 {
+ t.Fatalf("custom --approve missing from %v", args)
+ }
+ if len(args) < 2 || args[len(args)-2] != "--extension" || args[len(args)-1] != extensionPath {
+ t.Fatalf("args = %v, want --extension %s at the end", args, extensionPath)
+ }
+ if countArg(args, "--offline") != 1 {
+ t.Fatalf("custom --offline missing from %v", args)
+ }
+}
+
+func countArg(args []string, want string) int {
+ n := 0
+ for _, arg := range args {
+ if arg == want {
+ n++
+ }
+ }
+ return n
+}
+
func TestBuildPiArgsIgnoresSystemPrompt(t *testing.T) {
args := buildPiArgs("/tmp/s.jsonl", ExecOptions{
SystemPrompt: "the entire multica runtime brief",
@@ -1013,3 +1060,231 @@ func TestBuildPiArgsBareAndEmptyModels(t *testing.T) {
}
}
}
+
+func TestWritePiMcpExtensionIsolatesRegistrationErrorsAndLeavesProjectFile(t *testing.T) {
+ workDir := t.TempDir()
+ projectPath := filepath.Join(workDir, ".pi", "mcp.json")
+ if err := os.MkdirAll(filepath.Dir(projectPath), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ existing := []byte(`{"mcpServers":{"user":{"command":"echo"}}}`)
+ if err := os.WriteFile(projectPath, existing, 0o644); err != nil {
+ t.Fatal(err)
+ }
+
+ raw := json.RawMessage(`{
+ "mcpServers": {
+ "probe": {"command": "echo", "args": ["hi"]},
+ "remote": {"type": "http", "url": "http://127.0.0.1:12345/mcp"},
+ "bad name": {"command": "nope"},
+ "legacy": {"type": "sse", "url": "http://example.invalid"},
+ "bad-shape": "not-an-object"
+ }
+ }`)
+ path, err := writePiMcpExtension(raw)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if path == "" {
+ t.Fatal("expected an extension file")
+ }
+ t.Cleanup(func() { removePiMcpExtension(path) })
+
+ if !strings.HasPrefix(filepath.Base(filepath.Dir(path)), piMcpExtensionDirPrefix) {
+ t.Fatalf("extension dir = %s, want %s prefix", path, piMcpExtensionDirPrefix)
+ }
+ if filepath.Base(path) != "mcp-extension.mjs" {
+ t.Fatalf("extension file = %s", path)
+ }
+ info, err := os.Stat(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if info.Mode().Perm() != 0o600 {
+ t.Fatalf("extension mode = %o, want 600", info.Mode().Perm())
+ }
+ script, err := os.ReadFile(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ text := string(script)
+ for _, want := range []string{
+ "registerMcpServer", "probe", "echo", "remote", `\"type\":\"http\"`,
+ "127.0.0.1:12345/mcp", "bad name", "legacy", "bad-shape", "try {", "catch (error)",
+ } {
+ if !strings.Contains(text, want) {
+ t.Fatalf("script missing %q:\n%s", want, text)
+ }
+ }
+ if !strings.Contains(text, "could not register MCP server") {
+ t.Fatalf("script does not report isolated registration failures:\n%s", text)
+ }
+
+ data, err := os.ReadFile(projectPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if string(data) != string(existing) {
+ t.Fatalf("project mcp.json changed to %s", data)
+ }
+
+ args := buildPiArgs("/tmp/s.jsonl", ExecOptions{piMcpExtensionPath: path}, slog.Default())
+ if len(args) < 2 || args[len(args)-2] != "--extension" || args[len(args)-1] != path {
+ t.Fatalf("args = %v, want extension %s", args, path)
+ }
+ if countArg(args, "--approve") != 0 {
+ t.Fatalf("--approve present in %v", args)
+ }
+}
+
+func TestWritePiMcpExtensionSkipsUnmanagedAndEmpty(t *testing.T) {
+ for _, raw := range []json.RawMessage{
+ nil,
+ json.RawMessage("null"),
+ json.RawMessage(`{}`),
+ json.RawMessage(`{"mcpServers":{}}`),
+ json.RawMessage(`{"mcpServers":null}`),
+ } {
+ path, err := writePiMcpExtension(raw)
+ if err != nil {
+ t.Fatalf("writePiMcpExtension(%s): %v", raw, err)
+ }
+ if path != "" {
+ removePiMcpExtension(path)
+ t.Fatalf("writePiMcpExtension(%s) wrote %s", raw, path)
+ }
+ }
+}
+
+func TestPreparePiMcpExtensionRejectsOldBuiltinOnlyWhenServersPresent(t *testing.T) {
+ t.Setenv("TMPDIR", t.TempDir())
+ raw := json.RawMessage(`{"mcpServers":{"probe":{"command":"echo"}}}`)
+ backend := &piBackend{
+ providerLabel: "pi",
+ cfg: Config{
+ BuiltinRuntime: true,
+ CLIVersion: "pi 0.87.1",
+ },
+ }
+
+ for _, empty := range []json.RawMessage{
+ nil,
+ json.RawMessage("null"),
+ json.RawMessage(`{}`),
+ json.RawMessage(`{"mcpServers":{}}`),
+ json.RawMessage(`{"mcpServers":null}`),
+ } {
+ path, err := backend.preparePiMcpExtension(empty)
+ if err != nil || path != "" {
+ t.Fatalf("empty config %s on old Pi = (%q, %v), want no extension and no error", empty, path, err)
+ }
+ }
+ path, err := backend.preparePiMcpExtension(raw)
+ if err == nil {
+ removePiMcpExtension(path)
+ t.Fatal("managed MCP config was accepted by Pi below the MCP minimum")
+ }
+ for _, want := range []string{"0.87.1", piMcpMinVersion, "upgrade"} {
+ if !strings.Contains(err.Error(), want) {
+ t.Fatalf("old Pi error %q missing %q", err, want)
+ }
+ }
+ matches, globErr := filepath.Glob(filepath.Join(os.Getenv("TMPDIR"), piMcpExtensionDirPrefix+"*"))
+ if globErr != nil {
+ t.Fatal(globErr)
+ }
+ if len(matches) != 0 {
+ t.Fatalf("old Pi rejection leaked extension directories: %v", matches)
+ }
+}
+
+func TestPreparePiMcpExtensionRejectsUnverifiableBuiltinVersion(t *testing.T) {
+ t.Setenv("TMPDIR", t.TempDir())
+ raw := json.RawMessage(`{"mcpServers":{"probe":{"command":"echo"}}}`)
+
+ for _, version := range []string{"", "development-build"} {
+ backend := &piBackend{
+ providerLabel: "pi",
+ cfg: Config{
+ BuiltinRuntime: true,
+ CLIVersion: version,
+ },
+ }
+ path, err := backend.preparePiMcpExtension(raw)
+ if err == nil {
+ removePiMcpExtension(path)
+ t.Fatalf("builtin Pi version %q accepted managed MCP config", version)
+ }
+ for _, want := range []string{piMcpMinVersion, "could not verify", "upgrade"} {
+ if !strings.Contains(err.Error(), want) {
+ t.Fatalf("unverifiable Pi error %q missing %q", err, want)
+ }
+ }
+ }
+
+ matches, err := filepath.Glob(filepath.Join(os.Getenv("TMPDIR"), piMcpExtensionDirPrefix+"*"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(matches) != 0 {
+ t.Fatalf("unverifiable Pi rejection leaked extension directories: %v", matches)
+ }
+}
+
+func TestPreparePiMcpExtensionAllowsSupportedBuiltinAndCustomProtocol(t *testing.T) {
+ raw := json.RawMessage(`{"mcpServers":{"probe":{"command":"echo"}}}`)
+ for _, tc := range []struct {
+ name string
+ backend piBackend
+ }{
+ {
+ name: "supported builtin",
+ backend: piBackend{providerLabel: "pi", cfg: Config{
+ BuiltinRuntime: true,
+ CLIVersion: piMcpMinVersion,
+ }},
+ },
+ {
+ name: "custom protocol implementation",
+ backend: piBackend{providerLabel: "pi", cfg: Config{
+ BuiltinRuntime: false,
+ CLIVersion: "0.1.0",
+ }},
+ },
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ path, err := tc.backend.preparePiMcpExtension(raw)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if path == "" {
+ t.Fatal("expected MCP extension path")
+ }
+ removePiMcpExtension(path)
+ })
+ }
+}
+
+func TestRemovePiMcpExtensionIgnoresOtherPaths(t *testing.T) {
+ dir := t.TempDir()
+ path := filepath.Join(dir, "mcp-extension.mjs")
+ if err := os.WriteFile(path, []byte("keep"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ removePiMcpExtension(path)
+ if _, err := os.Stat(path); err != nil {
+ t.Fatalf("unrelated extension file was removed: %v", err)
+ }
+}
+
+func TestPreparePiMcpExtensionSkipsOmp(t *testing.T) {
+ backend := &piBackend{providerLabel: "omp"}
+ path, err := backend.preparePiMcpExtension(json.RawMessage(`{"mcpServers":{"probe":{"command":"echo"}}}`))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if path != "" {
+ removePiMcpExtension(path)
+ t.Fatalf("omp wrote a pi extension at %s", path)
+ }
+}