Skip to content

Commit 47c4e2c

Browse files
fix(server): serve the t3 mcp endpoint to devin over a stdio bridge
devin acp advertises mcpCapabilities { http: false, sse: false }, so the type: "http" t3-code MCP server was silently dropped and threads had no link_pull_request or other T3 tools. AcpSessionRuntime now accepts an mcpServers resolver that receives the agent's advertised mcpCapabilities after initialize, and the Devin adapter emits a stdio entry pointing at a self-contained Node bridge script written into the state directory. The bridge speaks newline-delimited JSON-RPC on stdio and relays to the streamable-HTTP endpoint, preserving the bearer header and replaying mcp-session-id / mcp-protocol-version on follow-up requests. Agents that do advertise http keep the direct entry, which also remains the fallback when the bridge script cannot be written. The adapter also merges the provider instance environment with the agent-device environment the same way the other ACP adapters do. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
1 parent d772206 commit 47c4e2c

8 files changed

Lines changed: 559 additions & 11 deletions

File tree

‎apps/server/scripts/acp-mock-agent.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -467,6 +467,13 @@ const program = Effect.gen(function* () {
467467
agentCapabilities: {
468468
loadSession: true,
469469
promptCapabilities: { image: true, embeddedContext: true },
470+
// The real CLI advertises no HTTP/SSE MCP transports; only stdio
471+
// MCP servers work for `devin acp`. T3_ACP_DEVIN_MCP_HTTP flips the
472+
// mock to an http-capable agent for the transport-selection tests.
473+
mcpCapabilities:
474+
process.env.T3_ACP_DEVIN_MCP_HTTP === "1"
475+
? { http: true, sse: false }
476+
: { http: false, sse: false },
470477
},
471478
authMethods: [{ id: "devin-browser", name: "Sign in with Devin" }],
472479
};
Lines changed: 170 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,170 @@
1+
// @effect-diagnostics nodeBuiltinImport:off globalDate:off globalTimers:off
2+
import * as NodeChildProcess from "node:child_process";
3+
import * as NodeFSP from "node:fs/promises";
4+
import * as NodeHttp from "node:http";
5+
import * as NodeOS from "node:os";
6+
import * as NodePath from "node:path";
7+
8+
import { describe, expect, it } from "vite-plus/test";
9+
10+
import {
11+
MCP_STDIO_BRIDGE_FILE_NAME,
12+
MCP_STDIO_BRIDGE_SOURCE,
13+
mcpStdioBridgeEntry,
14+
} from "./McpStdioBridge.ts";
15+
16+
interface SeenRequest {
17+
readonly method: string;
18+
readonly sessionId: string | undefined;
19+
readonly protocolVersion: string | undefined;
20+
readonly authorization: string | undefined;
21+
}
22+
23+
describe("McpStdioBridge", () => {
24+
it("builds a stdio MCP entry that launches the bridge under the current runtime", () => {
25+
const entry = mcpStdioBridgeEntry({
26+
bridgePath: "/tmp/state/mcp-stdio-bridge.mjs",
27+
endpoint: "http://127.0.0.1:9/mcp",
28+
authorizationHeader: "Bearer test",
29+
});
30+
expect(entry).toEqual({
31+
name: "t3-code",
32+
command: process.execPath,
33+
args: ["/tmp/state/mcp-stdio-bridge.mjs"],
34+
env: [
35+
{ name: "T3_MCP_ENDPOINT", value: "http://127.0.0.1:9/mcp" },
36+
{ name: "T3_MCP_AUTHORIZATION", value: "Bearer test" },
37+
],
38+
});
39+
});
40+
41+
it("relays stdio JSON-RPC to the streamable-HTTP endpoint and preserves session headers", async () => {
42+
const dir = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "t3-mcp-bridge-"));
43+
const bridgePath = NodePath.join(dir, MCP_STDIO_BRIDGE_FILE_NAME);
44+
await NodeFSP.writeFile(bridgePath, MCP_STDIO_BRIDGE_SOURCE);
45+
46+
const seen: SeenRequest[] = [];
47+
const server = NodeHttp.createServer((req, res) => {
48+
let body = "";
49+
req.on("data", (chunk) => {
50+
body += chunk;
51+
});
52+
req.on("end", () => {
53+
const parsed = JSON.parse(body) as { id?: number; method?: string };
54+
seen.push({
55+
method: parsed.method ?? "",
56+
sessionId: req.headers["mcp-session-id"] as string | undefined,
57+
protocolVersion: req.headers["mcp-protocol-version"] as string | undefined,
58+
authorization: req.headers.authorization,
59+
});
60+
switch (parsed.method) {
61+
case "initialize":
62+
res.writeHead(200, {
63+
"content-type": "application/json",
64+
"mcp-session-id": "stub-session-1",
65+
"mcp-protocol-version": "2025-06-18",
66+
});
67+
res.end(
68+
JSON.stringify({
69+
jsonrpc: "2.0",
70+
id: parsed.id,
71+
result: { protocolVersion: "2025-06-18" },
72+
}),
73+
);
74+
return;
75+
case "tools/list":
76+
res.writeHead(200, { "content-type": "application/json" });
77+
res.end(
78+
JSON.stringify({
79+
jsonrpc: "2.0",
80+
id: parsed.id,
81+
result: { tools: [{ name: "link_pull_request" }] },
82+
}),
83+
);
84+
return;
85+
case "tools/call":
86+
res.writeHead(200, { "content-type": "text/event-stream" });
87+
res.end(
88+
`data: ${JSON.stringify({ jsonrpc: "2.0", id: parsed.id, result: { ok: true } })}\n\n`,
89+
);
90+
return;
91+
case "boom/fail":
92+
res.writeHead(500, { "content-type": "text/plain" });
93+
res.end("upstream exploded");
94+
return;
95+
default:
96+
res.writeHead(202);
97+
res.end();
98+
}
99+
});
100+
});
101+
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
102+
const address = server.address();
103+
if (!address || typeof address === "string") throw new Error("stub server missing address");
104+
const endpoint = `http://127.0.0.1:${address.port}/mcp`;
105+
106+
const child = NodeChildProcess.spawn(process.execPath, [bridgePath], {
107+
env: { T3_MCP_ENDPOINT: endpoint, T3_MCP_AUTHORIZATION: "Bearer test-token" },
108+
stdio: ["pipe", "pipe", "pipe"],
109+
});
110+
const stdout: Array<Record<string, unknown>> = [];
111+
let stdoutBuffer = "";
112+
child.stdout.setEncoding("utf8");
113+
child.stdout.on("data", (chunk) => {
114+
stdoutBuffer += chunk;
115+
let index = stdoutBuffer.indexOf("\n");
116+
while (index >= 0) {
117+
const line = stdoutBuffer.slice(0, index).trim();
118+
stdoutBuffer = stdoutBuffer.slice(index + 1);
119+
if (line) stdout.push(JSON.parse(line) as Record<string, unknown>);
120+
index = stdoutBuffer.indexOf("\n");
121+
}
122+
});
123+
const send = (message: unknown) => child.stdin.write(`${JSON.stringify(message)}\n`);
124+
const waitForResponses = async (count: number) => {
125+
const deadline = Date.now() + 10_000;
126+
while (stdout.length < count && Date.now() < deadline) {
127+
await new Promise((resolve) => setTimeout(resolve, 25));
128+
}
129+
expect(stdout.length).toBeGreaterThanOrEqual(count);
130+
};
131+
132+
try {
133+
// Deliberately pipeline: the notification and requests are written before
134+
// the initialize response arrives; the bridge must hold them until it
135+
// has the session id.
136+
send({ jsonrpc: "2.0", id: 1, method: "initialize", params: {} });
137+
send({ jsonrpc: "2.0", method: "notifications/initialized" });
138+
send({ jsonrpc: "2.0", id: 2, method: "tools/list", params: {} });
139+
send({ jsonrpc: "2.0", id: 3, method: "tools/call", params: { name: "x" } });
140+
send({ jsonrpc: "2.0", id: 4, method: "boom/fail", params: {} });
141+
await waitForResponses(4);
142+
143+
const byId = new Map(
144+
stdout.filter((message) => "id" in message).map((message) => [message.id, message]),
145+
);
146+
expect(byId.get(1)).toMatchObject({ result: { protocolVersion: "2025-06-18" } });
147+
expect(byId.get(2)).toMatchObject({ result: { tools: [{ name: "link_pull_request" }] } });
148+
// SSE event payloads are decoded back into plain JSON-RPC messages.
149+
expect(byId.get(3)).toMatchObject({ result: { ok: true } });
150+
// A non-JSON error body becomes a JSON-RPC error carrying the request id.
151+
expect(byId.get(4)).toMatchObject({ error: { code: -32603 } });
152+
153+
const initialize = seen.find((request) => request.method === "initialize");
154+
expect(initialize?.authorization).toBe("Bearer test-token");
155+
156+
for (const method of ["notifications/initialized", "tools/list", "tools/call", "boom/fail"]) {
157+
const request = seen.find((entry) => entry.method === method);
158+
expect(request?.sessionId).toBe("stub-session-1");
159+
expect(request?.protocolVersion).toBe("2025-06-18");
160+
expect(request?.authorization).toBe("Bearer test-token");
161+
}
162+
// The notification gets no JSON-RPC response on stdout.
163+
expect(stdout.every((message) => message.method !== "notifications/initialized")).toBe(true);
164+
} finally {
165+
child.kill();
166+
server.close();
167+
await NodeFSP.rm(dir, { recursive: true, force: true });
168+
}
169+
});
170+
});
Lines changed: 187 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,187 @@
1+
import type * as PlatformError from "effect/PlatformError";
2+
import * as Effect from "effect/Effect";
3+
import * as FileSystem from "effect/FileSystem";
4+
import * as Path from "effect/Path";
5+
import type * as EffectAcpSchema from "effect-acp/schema";
6+
7+
/**
8+
* Self-contained stdio ↔ streamable-HTTP MCP bridge.
9+
*
10+
* ACP agents that only accept stdio MCP servers (Devin's `devin acp` advertises
11+
* `mcpCapabilities: { http: false, sse: false }`) cannot consume the T3 Code
12+
* streamable-HTTP MCP endpoint directly. We write this script into the state
13+
* directory and register it as `node <path>` so the agent launches it like any
14+
* other stdio MCP server.
15+
*
16+
* The script must be plain JavaScript: it runs under whatever Node binary hosts
17+
* the server, with no build step and no repo imports. stdout is reserved for
18+
* JSON-RPC; everything diagnostic goes to stderr.
19+
*/
20+
export const MCP_STDIO_BRIDGE_SOURCE = `#!/usr/bin/env node
21+
import { createInterface } from "node:readline";
22+
23+
const endpoint = process.env.T3_MCP_ENDPOINT;
24+
const authorization = process.env.T3_MCP_AUTHORIZATION;
25+
if (!endpoint) {
26+
process.stderr.write("T3_MCP_ENDPOINT is required\\n");
27+
process.exit(2);
28+
}
29+
30+
let sessionId;
31+
let protocolVersion;
32+
// Followers must not reach the stateful endpoint before "initialize" returns
33+
// its mcp-session-id header, so non-initialize messages await this promise.
34+
let sessionReady;
35+
let pendingWrites = Promise.resolve();
36+
const writer = process.stdout;
37+
38+
function writeMessage(message) {
39+
pendingWrites = pendingWrites.then(
40+
() =>
41+
new Promise((resolve) => {
42+
writer.write(JSON.stringify(message) + "\\n", () => resolve());
43+
}),
44+
);
45+
}
46+
47+
function respondError(id, message) {
48+
writeMessage({ jsonrpc: "2.0", id: id ?? null, error: { code: -32603, message } });
49+
}
50+
51+
async function postMessage(line, parsed) {
52+
const isInitialize = parsed && parsed.method === "initialize";
53+
if (!isInitialize && !sessionId && sessionReady) {
54+
await sessionReady;
55+
}
56+
const headers = {
57+
"content-type": "application/json",
58+
accept: "application/json, text/event-stream",
59+
};
60+
if (authorization) headers.authorization = authorization;
61+
if (sessionId) headers["mcp-session-id"] = sessionId;
62+
if (protocolVersion) headers["mcp-protocol-version"] = protocolVersion;
63+
64+
const response = await fetch(endpoint, { method: "POST", headers, body: line });
65+
sessionId = response.headers.get("mcp-session-id") ?? sessionId;
66+
protocolVersion = response.headers.get("mcp-protocol-version") ?? protocolVersion;
67+
68+
const contentType = response.headers.get("content-type") ?? "";
69+
if (contentType.includes("text/event-stream")) {
70+
for (const message of parseSseEvents(await response.text())) {
71+
writeMessage(message);
72+
}
73+
return;
74+
}
75+
76+
const text = await response.text();
77+
if (text.trim()) {
78+
try {
79+
const payload = JSON.parse(text);
80+
for (const message of Array.isArray(payload) ? payload : [payload]) {
81+
writeMessage(message);
82+
}
83+
return;
84+
} catch {
85+
// Fall through and synthesize an error below.
86+
}
87+
}
88+
if (!response.ok && parsed && typeof parsed === "object" && "id" in parsed) {
89+
respondError(parsed.id, "MCP endpoint returned HTTP " + response.status + ".");
90+
}
91+
}
92+
93+
function* parseSseEvents(body) {
94+
let data = [];
95+
const flush = function* () {
96+
if (data.length === 0) return;
97+
try {
98+
yield JSON.parse(data.join("\\n"));
99+
} catch {
100+
// Ignore unparseable SSE payloads.
101+
}
102+
data = [];
103+
};
104+
for (const line of body.split(/\\r?\\n/)) {
105+
if (line.startsWith("data:")) {
106+
data.push(line.slice(5).trimStart());
107+
} else if (line.trim() === "") {
108+
yield* flush();
109+
}
110+
}
111+
yield* flush();
112+
}
113+
114+
const rl = createInterface({ input: process.stdin, crlfDelay: Infinity });
115+
116+
async function main() {
117+
for await (const line of rl) {
118+
const trimmed = line.trim();
119+
if (!trimmed) continue;
120+
let parsed;
121+
try {
122+
parsed = JSON.parse(trimmed);
123+
} catch {
124+
respondError(null, "Parse error");
125+
continue;
126+
}
127+
const pending = postMessage(trimmed, parsed).catch((error) => {
128+
if (parsed && typeof parsed === "object" && "id" in parsed) {
129+
respondError(parsed.id, String(error instanceof Error ? error.message : error));
130+
}
131+
});
132+
if (parsed && parsed.method === "initialize" && sessionReady === undefined) {
133+
sessionReady = pending.then(
134+
() => {},
135+
() => {},
136+
);
137+
}
138+
}
139+
await pendingWrites;
140+
}
141+
142+
main();
143+
`;
144+
145+
export const MCP_STDIO_BRIDGE_FILE_NAME = "mcp-stdio-bridge.mjs";
146+
147+
/**
148+
* Ensures the bridge script exists under `stateDir` and returns its absolute
149+
* path. Reuses an up-to-date copy so warm restarts do not rewrite the file.
150+
*/
151+
export const ensureMcpStdioBridge = (
152+
stateDir: string,
153+
): Effect.Effect<string, PlatformError.PlatformError, FileSystem.FileSystem | Path.Path> =>
154+
Effect.gen(function* () {
155+
const fileSystem = yield* FileSystem.FileSystem;
156+
const path = yield* Path.Path;
157+
const bridgePath = path.join(stateDir, MCP_STDIO_BRIDGE_FILE_NAME);
158+
const existing = yield* fileSystem.readFileString(bridgePath).pipe(Effect.option);
159+
if (existing._tag === "Some" && existing.value === MCP_STDIO_BRIDGE_SOURCE) {
160+
return bridgePath;
161+
}
162+
yield* fileSystem.makeDirectory(stateDir, { recursive: true });
163+
const tempPath = `${bridgePath}.${process.pid}.tmp`;
164+
yield* fileSystem.writeFileString(tempPath, MCP_STDIO_BRIDGE_SOURCE);
165+
yield* fileSystem.rename(tempPath, bridgePath);
166+
return bridgePath;
167+
});
168+
169+
/**
170+
* Builds the ACP `session/new` stdio MCP entry that launches the bridge. The
171+
* endpoint URL and bearer header travel through the child environment so the
172+
* bridge needs no arguments.
173+
*/
174+
export const mcpStdioBridgeEntry = (input: {
175+
readonly bridgePath: string;
176+
readonly endpoint: string;
177+
readonly authorizationHeader: string;
178+
readonly name?: string;
179+
}): EffectAcpSchema.McpServer => ({
180+
name: input.name ?? "t3-code",
181+
command: process.execPath,
182+
args: [input.bridgePath],
183+
env: [
184+
{ name: "T3_MCP_ENDPOINT", value: input.endpoint },
185+
{ name: "T3_MCP_AUTHORIZATION", value: input.authorizationHeader },
186+
],
187+
});

‎apps/server/src/provider/Drivers/DevinDriver.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -113,6 +113,7 @@ export const DevinDriver: ProviderDriver<DevinSettings, DevinDriverEnv> = {
113113

114114
const adapter = yield* makeDevinAdapter(effectiveConfig, {
115115
instanceId,
116+
environment: processEnv,
116117
...(eventLoggers.native ? { nativeEventLogger: eventLoggers.native } : {}),
117118
onSessionStarted: provider.onSessionStarted,
118119
onConfigOptionsUpdated: provider.onConfigOptionsUpdated,
@@ -129,7 +130,6 @@ export const DevinDriver: ProviderDriver<DevinSettings, DevinDriverEnv> = {
129130
makeDevinAcpRuntime({
130131
...input,
131132
devinSettings: effectiveConfig,
132-
environment: processEnv,
133133
childProcessSpawner: spawner,
134134
}).pipe(
135135
Effect.provideService(Crypto.Crypto, crypto),

0 commit comments

Comments
 (0)