mirror of
https://github.com/expo/eas-cli.git
synced 2026-11-24 06:06:09 -10:00
Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2d5a984d1b | ||
|
|
07f0ff7596 |
No files matched your search
@@ -0,0 +1,5 @@
|
||||
---
|
||||
'@expo/build-tools': minor
|
||||
---
|
||||
|
||||
Connect the agent of `eas/run_agent` to the HTTP MCP servers in its `mcp_servers` input, and stop the run when one of them does not connect.
|
||||
@@ -32,6 +32,7 @@ const inputs = {
|
||||
agent_run_id: { value: '0199b0a0-1111-7222-8333-444455556666' },
|
||||
max_duration_seconds: { value: 1800 },
|
||||
prompt: { value: 'Fix the failing test.' },
|
||||
mcp_servers: { value: undefined },
|
||||
};
|
||||
const env = {
|
||||
PATH: '/usr/local/bin:/usr/bin',
|
||||
@@ -109,6 +110,7 @@ describe(createRunAgentBuildFunction, () => {
|
||||
'CLAUDE_CODE_OAUTH_TOKEN',
|
||||
'HOME',
|
||||
'LANG',
|
||||
'MCP_CONNECTION_NONBLOCKING',
|
||||
'PATH',
|
||||
'TMPDIR',
|
||||
]);
|
||||
@@ -129,6 +131,36 @@ describe(createRunAgentBuildFunction, () => {
|
||||
}
|
||||
});
|
||||
|
||||
it('hands the user MCP servers to the agent run, with no headers when none are given', async () => {
|
||||
const runAgentSpy = jest.spyOn(agentRun, 'runAgentAsync').mockResolvedValue();
|
||||
try {
|
||||
await runAsync({
|
||||
inputs: {
|
||||
...inputs,
|
||||
mcp_servers: {
|
||||
value: {
|
||||
linear: {
|
||||
url: 'https://mcp.linear.test/mcp',
|
||||
headers: { Authorization: 'Bearer linear-token' },
|
||||
},
|
||||
'my-docs': { url: 'https://docs.example.test/mcp' },
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
expect(runAgentSpy.mock.calls[0][0].userMcpServers).toEqual({
|
||||
linear: {
|
||||
url: 'https://mcp.linear.test/mcp',
|
||||
headers: { Authorization: 'Bearer linear-token' },
|
||||
},
|
||||
'my-docs': { url: 'https://docs.example.test/mcp', headers: {} },
|
||||
});
|
||||
} finally {
|
||||
runAgentSpy.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
it.each([
|
||||
['wss://staging-mcp.expo.test', 'https://staging-mcp.expo.test/mcp'],
|
||||
['ws://localhost:8787', 'http://localhost:8787/mcp'],
|
||||
@@ -172,6 +204,14 @@ describe(createRunAgentBuildFunction, () => {
|
||||
['a negative duration', { inputs: { ...inputs, max_duration_seconds: { value: -300 } } }],
|
||||
['a fractional duration', { inputs: { ...inputs, max_duration_seconds: { value: 12.5 } } }],
|
||||
['an empty prompt', { inputs: { ...inputs, prompt: { value: '' } } }],
|
||||
[
|
||||
'an MCP server named like the Expo one',
|
||||
{ inputs: { ...inputs, mcp_servers: { value: { expo: { url: 'https://a.test/mcp' } } } } },
|
||||
],
|
||||
[
|
||||
'an MCP server name with an underscore',
|
||||
{ inputs: { ...inputs, mcp_servers: { value: { my_docs: { url: 'https://a.test/mcp' } } } } },
|
||||
],
|
||||
['no EXPO_TOKEN', { env: { ...env, EXPO_TOKEN: '' } }],
|
||||
['no PATH', { env: { ...env, PATH: '' } }],
|
||||
['no Expo API URL', { ctx: { ...ctx, expoApiV2BaseUrl: undefined } }],
|
||||
@@ -199,4 +239,32 @@ describe(createRunAgentBuildFunction, () => {
|
||||
'The "max_duration_seconds" input must be a positive whole number of seconds, but received "0".'
|
||||
);
|
||||
});
|
||||
|
||||
it('names the server and the field of each invalid MCP server', async () => {
|
||||
await expect(
|
||||
runAsync({
|
||||
inputs: {
|
||||
...inputs,
|
||||
mcp_servers: {
|
||||
value: {
|
||||
expo: { url: 'https://a.test/mcp' },
|
||||
my_docs: { url: 'https://a.test/mcp' },
|
||||
linear: { url: 'not a url' },
|
||||
jira: { url: 'https://a.test/mcp', headers: { 'X-N': 1, 'X-M': 2 } },
|
||||
notion: { url: 'https://a.test/mcp', headers: 'Bearer token' },
|
||||
sentry: 'https://a.test/mcp',
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
).rejects.toThrow(
|
||||
'The "mcp_servers" input must not have a server named "expo", because the Expo MCP server uses that name. ' +
|
||||
'The "mcp_servers" input has a server named "my_docs", but server names may contain only letters, digits and hyphens. ' +
|
||||
'The "url" of the MCP server "linear" must be a URL. ' +
|
||||
'The header "X-N" of the MCP server "jira" must be a string. ' +
|
||||
'The header "X-M" of the MCP server "jira" must be a string. ' +
|
||||
'The "headers" of the MCP server "notion" must be an object that maps header names to values. ' +
|
||||
'The MCP server "sentry" must be an object with a "url" and optional "headers".'
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -9,6 +9,7 @@ import { z } from 'zod';
|
||||
|
||||
import { CustomBuildContext } from '../../customBuildContext';
|
||||
import { AGENT_KINDS, runAgentAsync } from '../utils/agentRun';
|
||||
import { MCP_SERVER_NAME } from '../utils/agents/agent';
|
||||
|
||||
export function createRunAgentBuildFunction(ctx: CustomBuildContext): BuildFunction {
|
||||
return new BuildFunction({
|
||||
@@ -38,6 +39,11 @@ export function createRunAgentBuildFunction(ctx: CustomBuildContext): BuildFunct
|
||||
required: true,
|
||||
allowedValueTypeName: BuildStepInputValueTypeName.STRING,
|
||||
}),
|
||||
BuildStepInput.createProvider({
|
||||
id: 'mcp_servers',
|
||||
required: false,
|
||||
allowedValueTypeName: BuildStepInputValueTypeName.JSON,
|
||||
}),
|
||||
],
|
||||
fn: async (stepCtx, { inputs, env, signal }) => {
|
||||
const inputErrors = {
|
||||
@@ -45,7 +51,24 @@ export function createRunAgentBuildFunction(ctx: CustomBuildContext): BuildFunct
|
||||
agentRunId: `The "agent_run_id" input must be the UUID of an agent run, but received "${String(inputs.agent_run_id.value)}".`,
|
||||
maxDurationSeconds: `The "max_duration_seconds" input must be a positive whole number of seconds, but received "${String(inputs.max_duration_seconds.value)}".`,
|
||||
prompt: 'The "prompt" input must be a non-empty string.',
|
||||
mcpServers: {
|
||||
servers: 'The "mcp_servers" input must be an object that maps server names to servers.',
|
||||
name: (name: string) =>
|
||||
`The "mcp_servers" input has a server named "${name}", but server names may contain only letters, digits and hyphens.`,
|
||||
reservedName: `The "mcp_servers" input must not have a server named "${MCP_SERVER_NAME}", because the Expo MCP server uses that name.`,
|
||||
server: (name: string) =>
|
||||
`The MCP server "${name}" must be an object with a "url" and optional "headers".`,
|
||||
url: (name: string) => `The "url" of the MCP server "${name}" must be a URL.`,
|
||||
headers: (name: string) =>
|
||||
`The "headers" of the MCP server "${name}" must be an object that maps header names to values.`,
|
||||
header: (name: string, headerName: string) =>
|
||||
`The header "${headerName}" of the MCP server "${name}" must be a string.`,
|
||||
},
|
||||
};
|
||||
const mcpServerNameAt = (issuePath: PropertyKey[] | undefined): string =>
|
||||
String(issuePath?.[1]);
|
||||
const mcpServerHeaderNameAt = (issuePath: PropertyKey[] | undefined): string =>
|
||||
String(issuePath?.[3]);
|
||||
const parsedInputs = z
|
||||
.object({
|
||||
agent_kind: z.enum(AGENT_KINDS, { error: inputErrors.agentKind }),
|
||||
@@ -55,12 +78,55 @@ export function createRunAgentBuildFunction(ctx: CustomBuildContext): BuildFunct
|
||||
.int({ error: inputErrors.maxDurationSeconds })
|
||||
.positive({ error: inputErrors.maxDurationSeconds }),
|
||||
prompt: z.string({ error: inputErrors.prompt }).min(1, { error: inputErrors.prompt }),
|
||||
mcp_servers: z
|
||||
.record(
|
||||
z
|
||||
.string()
|
||||
.regex(/^[a-zA-Z0-9-]+$/)
|
||||
.refine(name => name !== MCP_SERVER_NAME),
|
||||
z.object(
|
||||
{
|
||||
url: z.url({
|
||||
error: ({ path }) => inputErrors.mcpServers.url(mcpServerNameAt(path)),
|
||||
}),
|
||||
headers: z
|
||||
.record(
|
||||
z.string(),
|
||||
z.string({
|
||||
error: ({ path }) =>
|
||||
inputErrors.mcpServers.header(
|
||||
mcpServerNameAt(path),
|
||||
mcpServerHeaderNameAt(path)
|
||||
),
|
||||
}),
|
||||
{
|
||||
error: ({ path }) => inputErrors.mcpServers.headers(mcpServerNameAt(path)),
|
||||
}
|
||||
)
|
||||
.default({}),
|
||||
},
|
||||
{ error: ({ path }) => inputErrors.mcpServers.server(mcpServerNameAt(path)) }
|
||||
),
|
||||
{
|
||||
error: issue => {
|
||||
if (issue.code !== 'invalid_key') {
|
||||
return inputErrors.mcpServers.servers;
|
||||
}
|
||||
const name = mcpServerNameAt(issue.path);
|
||||
return name === MCP_SERVER_NAME
|
||||
? inputErrors.mcpServers.reservedName
|
||||
: inputErrors.mcpServers.name(name);
|
||||
},
|
||||
}
|
||||
)
|
||||
.default({}),
|
||||
})
|
||||
.safeParse({
|
||||
agent_kind: inputs.agent_kind.value,
|
||||
agent_run_id: inputs.agent_run_id.value,
|
||||
max_duration_seconds: inputs.max_duration_seconds.value,
|
||||
prompt: inputs.prompt.value,
|
||||
mcp_servers: inputs.mcp_servers.value,
|
||||
});
|
||||
if (!parsedInputs.success) {
|
||||
throw createValidationError(parsedInputs.error);
|
||||
@@ -70,6 +136,7 @@ export function createRunAgentBuildFunction(ctx: CustomBuildContext): BuildFunct
|
||||
agent_run_id: agentRunId,
|
||||
max_duration_seconds: maxDurationSeconds,
|
||||
prompt,
|
||||
mcp_servers: userMcpServers,
|
||||
} = parsedInputs.data;
|
||||
const parsedEnv = z
|
||||
.object({
|
||||
@@ -120,6 +187,7 @@ export function createRunAgentBuildFunction(ctx: CustomBuildContext): BuildFunct
|
||||
expoToken,
|
||||
expoApiV2BaseUrl: ctx.expoApiV2BaseUrl,
|
||||
mcpUrl: mcpUrl.toString(),
|
||||
userMcpServers,
|
||||
pathEnv,
|
||||
npmCacheUrl,
|
||||
logger: stepCtx.logger,
|
||||
|
||||
@@ -137,6 +137,7 @@ function createOptions(
|
||||
expoToken: 'expo-token',
|
||||
expoApiV2BaseUrl: 'https://staging-api.expo.test/v2/',
|
||||
mcpUrl: 'https://staging-mcp.expo.test/mcp',
|
||||
userMcpServers: {},
|
||||
pathEnv: '/usr/local/bin:/usr/bin',
|
||||
npmCacheUrl: 'https://npm-cache.expo.test',
|
||||
logger: createMockLogger(),
|
||||
@@ -217,11 +218,91 @@ describe(runAgentAsync, () => {
|
||||
LANG: 'C.UTF-8',
|
||||
CLAUDE_CODE_OAUTH_TOKEN: 'anthropic-access-token',
|
||||
CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: '1',
|
||||
MCP_CONNECTION_NONBLOCKING: '0',
|
||||
});
|
||||
expect(agent.cwd).toBe(path.join(runDirectory, 'cwd'));
|
||||
expect(agent.stdin).toHaveBeenCalledWith('Fix the failing test.');
|
||||
});
|
||||
|
||||
it('gives Claude Code the user MCP servers next to the Expo one and allows their tools', async () => {
|
||||
leaseMock.mockResolvedValue(anthropicLease);
|
||||
const invocations = mockSpawn({
|
||||
onAgent: agent => {
|
||||
expect(JSON.parse(agent.readHomeFile('mcp.json').content).mcpServers).toEqual({
|
||||
expo: expect.objectContaining({ type: 'http', url: 'https://staging-mcp.expo.test/mcp' }),
|
||||
linear: {
|
||||
type: 'http',
|
||||
url: 'https://mcp.linear.test/mcp',
|
||||
headers: { Authorization: 'Bearer linear-token' },
|
||||
},
|
||||
docs: { type: 'http', url: 'https://docs.example.test/mcp', headers: {} },
|
||||
});
|
||||
agent.exit(0);
|
||||
},
|
||||
});
|
||||
|
||||
await runAgentAsync(
|
||||
createOptions({
|
||||
userMcpServers: {
|
||||
linear: {
|
||||
url: 'https://mcp.linear.test/mcp',
|
||||
headers: { Authorization: 'Bearer linear-token' },
|
||||
},
|
||||
docs: { url: 'https://docs.example.test/mcp', headers: {} },
|
||||
},
|
||||
})
|
||||
);
|
||||
|
||||
const { args } = invocations[0];
|
||||
expect(args.slice(args.indexOf('--allowedTools'), args.indexOf('--mcp-config'))).toEqual([
|
||||
'--allowedTools',
|
||||
'mcp__expo',
|
||||
'mcp__linear',
|
||||
'mcp__docs',
|
||||
]);
|
||||
});
|
||||
|
||||
it('stops Claude Code before the task when a user MCP server did not connect, whatever the Expo one did', async () => {
|
||||
leaseMock.mockResolvedValue(anthropicLease);
|
||||
const invocations = mockSpawn({
|
||||
onAgent: agent => {
|
||||
killProcessGroupMock.mockImplementationOnce((_child, signal) =>
|
||||
agent.exit(null, signal as NodeJS.Signals)
|
||||
);
|
||||
agent.child.stdout.write(
|
||||
`${JSON.stringify({
|
||||
type: 'system',
|
||||
subtype: 'init',
|
||||
mcp_servers: [
|
||||
{ name: 'expo', status: 'failed' },
|
||||
{ name: 'linear', status: 'connected' },
|
||||
{ name: 'jira', status: 'needs-auth' },
|
||||
],
|
||||
})}\n`
|
||||
);
|
||||
},
|
||||
});
|
||||
|
||||
await expect(
|
||||
runAgentAsync(
|
||||
createOptions({
|
||||
userMcpServers: {
|
||||
linear: { url: 'https://mcp.linear.test/mcp', headers: {} },
|
||||
jira: { url: 'https://mcp.jira.test/mcp', headers: {} },
|
||||
docs: { url: 'https://docs.example.test/mcp', headers: {} },
|
||||
},
|
||||
})
|
||||
)
|
||||
).rejects.toMatchObject({
|
||||
errorCode: 'EAS_RUN_AGENT_MCP_SERVER_NOT_CONNECTED',
|
||||
message: expect.stringContaining(': jira (needs-auth), docs (not started).'),
|
||||
});
|
||||
|
||||
expect(killProcessGroupMock.mock.calls[0]).toEqual([invocations[0].child, 'SIGTERM']);
|
||||
expect(invocations).toHaveLength(1);
|
||||
expect(leaseMock).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('writes the agent output as log lines', async () => {
|
||||
leaseMock.mockResolvedValue(anthropicLease);
|
||||
const logger = createMockLogger();
|
||||
@@ -395,6 +476,48 @@ describe(runAgentAsync, () => {
|
||||
expect(agent.stdin).toHaveBeenCalledWith('Fix the failing test.');
|
||||
});
|
||||
|
||||
it('requires the user MCP servers of Codex but not the Expo one', async () => {
|
||||
leaseMock.mockResolvedValue(openaiLease);
|
||||
mockSpawn({
|
||||
onAgent: agent => {
|
||||
const config = agent.readHomeFile('.codex/config.toml').content;
|
||||
expect(config.slice(config.indexOf('[mcp_servers.'))).toBe(
|
||||
[
|
||||
'[mcp_servers.expo]',
|
||||
'url = "https://staging-mcp.expo.test/mcp"',
|
||||
'default_tools_approval_mode = "approve"',
|
||||
'',
|
||||
'[mcp_servers.expo.http_headers]',
|
||||
'"Authorization" = "Bearer expo-token"',
|
||||
`"X-Expo-Agent-Run-Id" = "${agentRunId}"`,
|
||||
'',
|
||||
'[mcp_servers.linear]',
|
||||
'url = "https://mcp.linear.test/mcp"',
|
||||
'default_tools_approval_mode = "approve"',
|
||||
'required = true',
|
||||
'',
|
||||
'[mcp_servers.linear.http_headers]',
|
||||
'"Authorization" = "Bearer \\"linear\\" token"',
|
||||
'',
|
||||
].join('\n')
|
||||
);
|
||||
agent.exit(0);
|
||||
},
|
||||
});
|
||||
|
||||
await runAgentAsync(
|
||||
createOptions({
|
||||
agentKind: 'codex',
|
||||
userMcpServers: {
|
||||
linear: {
|
||||
url: 'https://mcp.linear.test/mcp',
|
||||
headers: { Authorization: 'Bearer "linear" token' },
|
||||
},
|
||||
},
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it('escalates to SIGKILL when the agent ignores the stop', async () => {
|
||||
jest.useFakeTimers({ doNotFake: ['nextTick', 'setImmediate', 'queueMicrotask'] });
|
||||
leaseMock.mockResolvedValue(anthropicLease);
|
||||
|
||||
@@ -8,7 +8,12 @@ import path from 'node:path';
|
||||
import readline from 'node:readline';
|
||||
|
||||
import { leaseAgentRunProviderCredentialsAsync } from './agentRunLease';
|
||||
import { type AgentCli, type AgentInvocation, type AgentLogMessage } from './agents/agent';
|
||||
import {
|
||||
type AgentCli,
|
||||
type AgentInvocation,
|
||||
type AgentLogMessage,
|
||||
type McpServer,
|
||||
} from './agents/agent';
|
||||
import { CLAUDE_CODE_CLI, prepareClaudeCodeAsync } from './agents/claude';
|
||||
import { CODEX_CLI, prepareCodexAsync } from './agents/codex';
|
||||
import { Sentry } from '../../sentry';
|
||||
@@ -32,6 +37,7 @@ export async function runAgentAsync({
|
||||
expoToken,
|
||||
expoApiV2BaseUrl,
|
||||
mcpUrl,
|
||||
userMcpServers,
|
||||
pathEnv,
|
||||
npmCacheUrl,
|
||||
logger,
|
||||
@@ -45,6 +51,7 @@ export async function runAgentAsync({
|
||||
expoApiV2BaseUrl: string;
|
||||
/** The Expo MCP server's streamable HTTP endpoint. */
|
||||
mcpUrl: string;
|
||||
userMcpServers: Record<string, McpServer>;
|
||||
pathEnv: string;
|
||||
npmCacheUrl?: string;
|
||||
logger: bunyan;
|
||||
@@ -105,6 +112,7 @@ export async function runAgentAsync({
|
||||
homeDirectory,
|
||||
minimalEnv,
|
||||
mcpServer,
|
||||
userMcpServers,
|
||||
prompt,
|
||||
credentials,
|
||||
isResuming,
|
||||
@@ -115,6 +123,7 @@ export async function runAgentAsync({
|
||||
homeDirectory,
|
||||
minimalEnv,
|
||||
mcpServer,
|
||||
userMcpServers,
|
||||
prompt,
|
||||
credentials,
|
||||
isResuming,
|
||||
@@ -165,6 +174,7 @@ async function runAgentProcessAsync({
|
||||
env,
|
||||
cwd,
|
||||
stdin,
|
||||
findFatalError,
|
||||
formatOutputLine,
|
||||
logger,
|
||||
signal,
|
||||
@@ -174,6 +184,7 @@ async function runAgentProcessAsync({
|
||||
env: Record<string, string>;
|
||||
cwd: string;
|
||||
stdin: string;
|
||||
findFatalError?: AgentInvocation['findFatalError'];
|
||||
formatOutputLine: AgentCli['formatOutputLine'];
|
||||
logger: bunyan;
|
||||
signal: AbortSignal;
|
||||
@@ -182,11 +193,22 @@ async function runAgentProcessAsync({
|
||||
// Detached, so the agent leads a process group that can be signaled as a whole.
|
||||
const child = spawn(command, args, { cwd, env, detached: true });
|
||||
const outputClosed = new Promise<void>(resolve => child.once('close', () => resolve()));
|
||||
let killTimer: NodeJS.Timeout | undefined;
|
||||
const stop = (): void => {
|
||||
if (killTimer) {
|
||||
return;
|
||||
}
|
||||
killProcessGroup(child, 'SIGTERM');
|
||||
killTimer = setTimeout(() => killProcessGroup(child, 'SIGKILL'), KILL_GRACE_PERIOD_MS);
|
||||
};
|
||||
let fatalError: Error | undefined;
|
||||
const stdoutLogger = logger.child({ source: 'stdout' });
|
||||
readline.createInterface({ input: child.stdout }).on('line', line => {
|
||||
let messages: AgentLogMessage[];
|
||||
let lineFatalError: Error | undefined;
|
||||
try {
|
||||
messages = formatOutputLine(line);
|
||||
lineFatalError = findFatalError?.(line);
|
||||
} catch (error) {
|
||||
// An exception in a readline listener is uncaught and would end the worker process.
|
||||
Sentry.capture('Could not format a line of the agent output', error as Error);
|
||||
@@ -195,6 +217,10 @@ async function runAgentProcessAsync({
|
||||
for (const { level, message } of messages) {
|
||||
stdoutLogger[level](message.trimEnd());
|
||||
}
|
||||
if (lineFatalError && !fatalError) {
|
||||
fatalError = lineFatalError;
|
||||
stop();
|
||||
}
|
||||
});
|
||||
const stderrLogger = logger.child({ source: 'stderr' });
|
||||
readline.createInterface({ input: child.stderr }).on('line', line => {
|
||||
@@ -204,14 +230,6 @@ async function runAgentProcessAsync({
|
||||
child.stdin.on('error', () => {});
|
||||
child.stdin.end(stdin);
|
||||
|
||||
let killTimer: NodeJS.Timeout | undefined;
|
||||
const stop = (): void => {
|
||||
if (killTimer) {
|
||||
return;
|
||||
}
|
||||
killProcessGroup(child, 'SIGTERM');
|
||||
killTimer = setTimeout(() => killProcessGroup(child, 'SIGKILL'), KILL_GRACE_PERIOD_MS);
|
||||
};
|
||||
signal.addEventListener('abort', stop);
|
||||
let exitCode: number | null;
|
||||
let exitSignal: NodeJS.Signals | null;
|
||||
@@ -241,5 +259,8 @@ async function runAgentProcessAsync({
|
||||
clearTimeout(outputGraceTimer);
|
||||
|
||||
signal.throwIfAborted();
|
||||
if (fatalError) {
|
||||
throw fatalError;
|
||||
}
|
||||
return { exitCode, exitSignal };
|
||||
}
|
||||
@@ -15,6 +15,7 @@ export interface AgentInvocation {
|
||||
env: Record<string, string>;
|
||||
stdin: string;
|
||||
secrets: string[];
|
||||
findFatalError?(outputLine: string): Error | undefined;
|
||||
}
|
||||
|
||||
export interface AgentLogMessage {
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { UserError } from '@expo/eas-build-job';
|
||||
import fs from 'node:fs/promises';
|
||||
import path from 'node:path';
|
||||
import { z } from 'zod';
|
||||
@@ -28,6 +29,7 @@ export async function prepareClaudeCodeAsync({
|
||||
homeDirectory,
|
||||
minimalEnv,
|
||||
mcpServer,
|
||||
userMcpServers,
|
||||
prompt,
|
||||
credentials,
|
||||
isResuming,
|
||||
@@ -35,6 +37,7 @@ export async function prepareClaudeCodeAsync({
|
||||
homeDirectory: string;
|
||||
minimalEnv: Record<string, string>;
|
||||
mcpServer: McpServer;
|
||||
userMcpServers: Record<string, McpServer>;
|
||||
prompt: string;
|
||||
credentials: AgentRunProviderCredentials;
|
||||
isResuming: boolean;
|
||||
@@ -42,10 +45,15 @@ export async function prepareClaudeCodeAsync({
|
||||
if (credentials.provider !== 'anthropic') {
|
||||
throw createProviderMismatchError('Claude Code', credentials);
|
||||
}
|
||||
const mcpServers = { [MCP_SERVER_NAME]: mcpServer, ...userMcpServers };
|
||||
const mcpConfigPath = path.join(homeDirectory, 'mcp.json');
|
||||
await fs.writeFile(
|
||||
mcpConfigPath,
|
||||
JSON.stringify({ mcpServers: { [MCP_SERVER_NAME]: { type: 'http', ...mcpServer } } }),
|
||||
JSON.stringify({
|
||||
mcpServers: Object.fromEntries(
|
||||
Object.entries(mcpServers).map(([name, server]) => [name, { type: 'http', ...server }])
|
||||
),
|
||||
}),
|
||||
{ mode: 0o600 }
|
||||
);
|
||||
return {
|
||||
@@ -54,21 +62,45 @@ export async function prepareClaudeCodeAsync({
|
||||
...(isResuming ? ['--continue'] : []),
|
||||
// Print mode requires `--verbose` for `stream-json`.
|
||||
...['--output-format', 'stream-json', '--verbose'],
|
||||
// No built-in tools. Print mode denies any tool without an allow rule, so the MCP server
|
||||
// No built-in tools. Print mode denies any tool without an allow rule, so each MCP server
|
||||
// gets one.
|
||||
...['--tools', '', '--allowedTools', `mcp__${MCP_SERVER_NAME}`],
|
||||
...['--tools', '', '--allowedTools', ...Object.keys(mcpServers).map(name => `mcp__${name}`)],
|
||||
...['--mcp-config', mcpConfigPath, '--strict-mcp-config'],
|
||||
],
|
||||
env: {
|
||||
...minimalEnv,
|
||||
CLAUDE_CODE_OAUTH_TOKEN: credentials.accessToken,
|
||||
CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: '1',
|
||||
MCP_CONNECTION_NONBLOCKING: '0',
|
||||
},
|
||||
stdin: isResuming ? createContinuationPrompt(prompt) : prompt,
|
||||
secrets: [credentials.accessToken],
|
||||
findFatalError: outputLine =>
|
||||
findUnconnectedMcpServersError(outputLine, Object.keys(userMcpServers)),
|
||||
};
|
||||
}
|
||||
|
||||
function findUnconnectedMcpServersError(
|
||||
outputLine: string,
|
||||
requiredServerNames: string[]
|
||||
): UserError | undefined {
|
||||
const event = ClaudeCodeEventSchema.safeParse(parseJsonLine(outputLine));
|
||||
if (!event.success || event.data.type !== 'system') {
|
||||
return undefined;
|
||||
}
|
||||
const statusByName = new Map(event.data.mcp_servers.map(server => [server.name, server.status]));
|
||||
const unconnectedServers = requiredServerNames
|
||||
.filter(name => statusByName.get(name) !== 'connected')
|
||||
.map(name => `${name} (${statusByName.get(name) ?? 'not started'})`);
|
||||
if (unconnectedServers.length === 0) {
|
||||
return undefined;
|
||||
}
|
||||
return new UserError(
|
||||
'EAS_RUN_AGENT_MCP_SERVER_NOT_CONNECTED',
|
||||
`The agent could not connect to these MCP servers from "mcp_servers": ${unconnectedServers.join(', ')}. It was stopped before it started the task. Check that each server's URL is reachable from EAS and that its headers authenticate the request, then start the agent run again.`
|
||||
);
|
||||
}
|
||||
|
||||
const AssistantBlockSchema = z.discriminatedUnion('type', [
|
||||
z.object({ type: z.literal('text'), text: z.string() }),
|
||||
z.object({
|
||||
|
||||
@@ -27,6 +27,7 @@ export async function prepareCodexAsync({
|
||||
homeDirectory,
|
||||
minimalEnv,
|
||||
mcpServer,
|
||||
userMcpServers,
|
||||
prompt,
|
||||
credentials,
|
||||
isResuming,
|
||||
@@ -34,6 +35,7 @@ export async function prepareCodexAsync({
|
||||
homeDirectory: string;
|
||||
minimalEnv: Record<string, string>;
|
||||
mcpServer: McpServer;
|
||||
userMcpServers: Record<string, McpServer>;
|
||||
prompt: string;
|
||||
credentials: AgentRunProviderCredentials;
|
||||
isResuming: boolean;
|
||||
@@ -67,17 +69,10 @@ export async function prepareCodexAsync({
|
||||
'[analytics]',
|
||||
'enabled = false',
|
||||
'',
|
||||
`[mcp_servers.${MCP_SERVER_NAME}]`,
|
||||
// JSON strings are valid TOML basic strings.
|
||||
`url = ${JSON.stringify(mcpServer.url)}`,
|
||||
// `approval_policy` would otherwise refuse the server's tools that are not read-only.
|
||||
'default_tools_approval_mode = "approve"',
|
||||
'',
|
||||
`[mcp_servers.${MCP_SERVER_NAME}.http_headers]`,
|
||||
...Object.entries(mcpServer.headers).map(
|
||||
([name, value]) => `${JSON.stringify(name)} = ${JSON.stringify(value)}`
|
||||
...createMcpServerConfigLines(MCP_SERVER_NAME, mcpServer, { isRequired: false }),
|
||||
...Object.entries(userMcpServers).flatMap(([name, server]) =>
|
||||
createMcpServerConfigLines(name, server, { isRequired: true })
|
||||
),
|
||||
'',
|
||||
].join('\n'),
|
||||
{ mode: 0o600 }
|
||||
);
|
||||
@@ -111,6 +106,27 @@ export async function prepareCodexAsync({
|
||||
};
|
||||
}
|
||||
|
||||
function createMcpServerConfigLines(
|
||||
name: string,
|
||||
server: McpServer,
|
||||
{ isRequired }: { isRequired: boolean }
|
||||
): string[] {
|
||||
return [
|
||||
`[mcp_servers.${name}]`,
|
||||
// JSON strings are valid TOML basic strings.
|
||||
`url = ${JSON.stringify(server.url)}`,
|
||||
// `approval_policy` would otherwise refuse the server's tools that are not read-only.
|
||||
'default_tools_approval_mode = "approve"',
|
||||
...(isRequired ? ['required = true'] : []),
|
||||
'',
|
||||
`[mcp_servers.${name}.http_headers]`,
|
||||
...Object.entries(server.headers).map(
|
||||
([headerName, value]) => `${JSON.stringify(headerName)} = ${JSON.stringify(value)}`
|
||||
),
|
||||
'',
|
||||
];
|
||||
}
|
||||
|
||||
const CodexItemSchema = z.discriminatedUnion('type', [
|
||||
z.object({ type: z.literal('agent_message'), text: z.string() }),
|
||||
z.object({
|
||||
|
||||
Reference in new issue
Block a user