Skip to content
Closed
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
2 changes: 1 addition & 1 deletion packages/opencode/src/session/tools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -405,7 +405,7 @@ export const resolve = Effect.fn("SessionTools.resolve")(function* (input: {
{ args },
)
const result: Awaited<ReturnType<NonNullable<typeof execute>>> = yield* Effect.gen(function* () {
yield* ctx.ask({ permission: key, metadata: {}, patterns: ["*"], always: ["*"] })
yield* ctx.ask({ permission: key, metadata: args, patterns: [key], always: [key] })
return yield* Effect.promise(() => execute(args, opts))
}).pipe(
Effect.withSpan("Tool.execute", {
Expand Down
112 changes: 110 additions & 2 deletions packages/opencode/test/session/prompt.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@ import { Cause, Deferred, Duration, Effect, Exit, Fiber, Layer } from "effect"
import path from "path"
import { fileURLToPath } from "url"
import { NamedError } from "@opencode-ai/core/util/error"
import { PermissionV1 } from "@opencode-ai/core/v1/permission"
import type { Client } from "@modelcontextprotocol/sdk/client/index.js"
import type { Tool } from "@modelcontextprotocol/sdk/types.js"
import { Agent as AgentSvc } from "../../src/agent/agent"
import { BackgroundJob } from "@/background/job"
import { Command } from "../../src/command"
Expand Down Expand Up @@ -221,12 +224,16 @@ function makePrompt(input?: { mcpInstructions?: MCP.ServerInstructions[]; proces
return LayerNode.compile(promptRoot, replacements)
}

function makeHttp(input?: { mcpInstructions?: MCP.ServerInstructions[]; processor?: "blocking" }) {
function makeHttp(input?: {
mcpInstructions?: MCP.ServerInstructions[]
processor?: "blocking"
mcp?: Layer.Layer<MCP.Service>
}) {
const root = LayerNode.group([promptRoot, testLLMServerNode])
const replacements = [
[SessionSummary.node, summary],
[LSP.node, lsp],
[MCP.node, makeMcp(input?.mcpInstructions)],
[MCP.node, input?.mcp ?? makeMcp(input?.mcpInstructions)],
[RuntimeFlags.node, runtimeFlags],
] as const
if (input?.processor === "blocking") {
Expand Down Expand Up @@ -2468,3 +2475,104 @@ noLLMServer.instance(
}),
30_000,
)

// MCP wrapper permission payload — see packages/opencode/src/session/tools.ts.
// The wrapper must forward the tool name as the permission key/pattern and the
// raw tool arguments as metadata so SDK consumers can reason about the call.
const mcpEchoCalls: Array<{ name: string; arguments: Record<string, unknown> | undefined }> = []
const mcpEchoToolDef = {
name: "say",
description: "echo back the greeting",
inputSchema: {
type: "object",
properties: { greeting: { type: "string" } },
required: ["greeting"],
additionalProperties: false,
},
} satisfies Tool
const mcpEchoClient = {
callTool: async (request: { name: string; arguments?: Record<string, unknown> }) => {
mcpEchoCalls.push({ name: request.name, arguments: request.arguments })
return { content: [{ type: "text" as const, text: "ok" }] }
},
} as unknown as Client
const mcpWithEchoTool = Layer.succeed(
MCP.Service,
MCP.Service.of({
status: () => Effect.succeed({}),
clients: () => Effect.succeed({}),
instructions: () => Effect.succeed([]),
tools: () =>
Effect.succeed({
echo_say: { def: mcpEchoToolDef, client: mcpEchoClient },
}),
prompts: () => Effect.succeed({}),
resources: () => Effect.succeed({}),
resourceTemplates: () => Effect.succeed({}),
add: () => Effect.succeed({ status: { status: "disabled" as const } }),
connect: () => Effect.void,
disconnect: () => Effect.void,
getPrompt: () => Effect.succeed(undefined),
readResource: () => Effect.succeed(undefined),
startAuth: () => Effect.die("unexpected MCP auth in prompt-effect tests"),
authenticate: () => Effect.die("unexpected MCP auth in prompt-effect tests"),
finishAuth: () => Effect.die("unexpected MCP auth in prompt-effect tests"),
removeAuth: () => Effect.void,
supportsOAuth: () => Effect.succeed(false),
hasStoredTokens: () => Effect.succeed(false),
getAuthStatus: () => Effect.succeed("not_authenticated" as const),
}),
)

const mcpIt = testEffect(makeHttp({ mcp: mcpWithEchoTool }))

mcpIt.instance("mcp tool ask publishes tool name and args (regression: #19549)", () =>
Effect.gen(function* () {
mcpEchoCalls.length = 0
const { llm } = yield* useServerConfig(providerCfg)
const events = yield* EventV2Bridge.Service
const seen = yield* Deferred.make<PermissionV1.Request>()
const unsub = yield* events.listen((event) => {
if (event.type === Permission.Event.Asked.type)
Deferred.doneUnsafe(seen, Effect.succeed(event.data as PermissionV1.Request))
return Effect.void
})
yield* Effect.addFinalizer(() => unsub)

const prompt = yield* SessionPrompt.Service
const permission = yield* Permission.Service
const sessions = yield* Session.Service
const session = yield* sessions.create({
title: "MCP wrapper ask",
permission: [{ permission: "*", pattern: "*", action: "ask" }],
})

yield* prompt.prompt({
sessionID: session.id,
agent: "build",
noReply: true,
parts: [{ type: "text", text: "say hi" }],
})
yield* llm.tool("echo_say", { greeting: "hi" })
yield* llm.text("done")

const fiber = yield* prompt.loop({ sessionID: session.id }).pipe(Effect.forkChild)

const request = yield* Deferred.await(seen).pipe(
Effect.timeoutOrElse({
duration: Duration.seconds(5),
orElse: () => Effect.fail(new Error("timed out waiting for permission.asked")),
}),
)
expect(request.permission).toBe("echo_say")
expect(request.patterns).toEqual(["echo_say"])
expect(request.always).toEqual(["echo_say"])
expect(request.metadata).toEqual({ greeting: "hi" })

yield* permission.reply({ requestID: request.id, reply: "once" })

const exit = yield* Fiber.await(fiber)
expect(Exit.isSuccess(exit)).toBe(true)
expect(mcpEchoCalls).toEqual([{ name: "say", arguments: { greeting: "hi" } }])
}),
)
Loading