Skip to content

Commit fe5b952

Browse files
RulaKhaledclaude
andauthored
feat(server-utils): Emit execute_tool spans for Anthropic's beta.sessions.events.toolRunner() (#25554)
`beta.sessions.events.toolRunner()` runs the user's tools for a Managed Agents session, but its tool calls got no span. The runner turns a throw into an error result for the model, so nobody saw a failing tool either. #25320 only covered `beta.messages.toolRunner()`. The session runner calls the same `run(input, ctx)` as the messages runner and keeps its tools on a public `tools` field, so this reuses the wrapping from #25320. It has no `addTools()`, so it can only run the tools it was created with. On the orchestrion path the hook sits on the `SessionToolRunner` constructor instead of `toolRunner()`, because the SDK's `EnvironmentWorker` creates runners with `new SessionToolRunner()` directly. `instrumentAnthropicAiClient` can only wrap `toolRunner()`, so it doesn't see those runners. Supported from SDK 0.97.0, the first version with the session runner. **Known limitation.** A tool that stops on the session runner's 120s timeout is recorded as cancelled, like a user abort, because the SDK aborts the same signal for both. Fixes #25446 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 7030f21 commit fe5b952

7 files changed

Lines changed: 277 additions & 9 deletions

File tree

Lines changed: 107 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,107 @@
1+
import Anthropic from '@anthropic-ai/sdk';
2+
import { SessionToolRunner } from '@anthropic-ai/sdk/resources/beta/sessions/events';
3+
import * as Sentry from '@sentry/node';
4+
import express from 'express';
5+
6+
const STREAM_EVENTS = {
7+
sesn_weather: [
8+
{ type: 'agent.tool_use', id: 'sevt_weather', name: 'weather', input: { city: 'Vienna' } },
9+
{ type: 'agent.tool_use', id: 'sevt_explode', name: 'explode', input: {} },
10+
{ type: 'session.status_terminated', id: 'sevt_weather_end' },
11+
],
12+
// Served by a runner built with `new SessionToolRunner()`, as `EnvironmentWorker` does.
13+
sesn_direct: [
14+
{ type: 'agent.tool_use', id: 'sevt_read', name: 'read', input: { file_path: 'README.md' } },
15+
{ type: 'session.status_terminated', id: 'sevt_direct_end' },
16+
],
17+
};
18+
19+
function startMockSessionsServer() {
20+
const app = express();
21+
app.use(express.json());
22+
23+
app.get('/anthropic/v1/sessions/:sessionId/events/stream', (req, res) => {
24+
res.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', Connection: 'keep-alive' });
25+
26+
const events = STREAM_EVENTS[req.params.sessionId];
27+
events.forEach((event, index) => {
28+
setTimeout(() => {
29+
res.write(`event: ${event.type}\n`);
30+
res.write(`data: ${JSON.stringify(event)}\n\n`);
31+
if (index === events.length - 1) {
32+
res.end();
33+
}
34+
}, index * 10);
35+
});
36+
});
37+
app.get('/anthropic/v1/sessions/:sessionId/events', (_req, res) => {
38+
res.json({ data: [], next_page: null });
39+
});
40+
app.post('/anthropic/v1/sessions/:sessionId/events', (_req, res) => {
41+
res.json({ data: [] });
42+
});
43+
44+
return new Promise(resolve => {
45+
const server = app.listen(0, () => {
46+
resolve(server);
47+
});
48+
});
49+
}
50+
51+
async function drain(runner) {
52+
for await (const _call of runner) {
53+
// drain
54+
}
55+
}
56+
57+
async function run() {
58+
const server = await startMockSessionsServer();
59+
60+
await Sentry.startSpan({ op: 'function', name: 'main' }, async () => {
61+
const client = new Anthropic({
62+
apiKey: 'mock-api-key',
63+
baseURL: `http://localhost:${server.address().port}/anthropic`,
64+
});
65+
66+
await drain(
67+
client.beta.sessions.events.toolRunner('sesn_weather', {
68+
tools: [
69+
{
70+
name: 'weather',
71+
description: 'Get the weather by city',
72+
input_schema: { type: 'object', properties: { city: { type: 'string' } } },
73+
run: () => 'sunny',
74+
},
75+
{
76+
name: 'explode',
77+
description: 'Always fails',
78+
input_schema: { type: 'object', properties: {} },
79+
run: () => {
80+
throw new Error('Tool exploded');
81+
},
82+
},
83+
],
84+
}),
85+
);
86+
87+
await drain(
88+
new SessionToolRunner('sesn_direct', {
89+
client,
90+
tools: [
91+
{
92+
name: 'read',
93+
description: 'Read a file',
94+
input_schema: { type: 'object', properties: { file_path: { type: 'string' } } },
95+
run: () => '# Weather app',
96+
},
97+
],
98+
}),
99+
);
100+
});
101+
102+
await Sentry.flush(2000);
103+
104+
server.close();
105+
}
106+
107+
run();

‎dev-packages/node-integration-tests/suites/tracing/anthropic/v0.129/test.ts‎

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -137,4 +137,67 @@ describe('Anthropic integration (0.129)', () => {
137137
},
138138
},
139139
);
140+
141+
createEsmAndCjsTests(
142+
__dirname,
143+
'scenario-session-tool-runner.mjs',
144+
'instrument.mjs',
145+
(createRunner, test) => {
146+
test('emits an execute_tool span for each tool a session runner runs, however it was created', async () => {
147+
let receivedEvent: Event | undefined;
148+
let receivedSpans: SerializedStreamedSpanContainer['items'] = [];
149+
150+
await createRunner()
151+
.unordered()
152+
.expect({
153+
span: container => {
154+
expect(container.items.find(span => span.is_segment && span.name === 'main')).toBeDefined();
155+
receivedSpans = container.items;
156+
},
157+
})
158+
.expect({
159+
event: event => {
160+
receivedEvent = event;
161+
},
162+
})
163+
.start()
164+
.completed();
165+
166+
const main = receivedSpans.find(span => span.is_segment && span.name === 'main')!;
167+
const toolSpans = receivedSpans.filter(span => span.attributes[SENTRY_OP]?.value === GEN_AI_EXECUTE_TOOL);
168+
expect(toolSpans).toHaveLength(3);
169+
const weather = toolSpans.find(span => span.attributes[GEN_AI_TOOL_NAME]?.value === 'weather')!;
170+
const explode = toolSpans.find(span => span.attributes[GEN_AI_TOOL_NAME]?.value === 'explode')!;
171+
const read = toolSpans.find(span => span.attributes[GEN_AI_TOOL_NAME]?.value === 'read')!;
172+
173+
expect(weather).toMatchObject({
174+
name: 'execute_tool weather',
175+
parent_span_id: main.span_id,
176+
status: 'ok',
177+
attributes: expect.objectContaining({
178+
[GEN_AI_TOOL_CALL_ID_ATTRIBUTE]: { type: 'string', value: 'sevt_weather' },
179+
}),
180+
});
181+
expect(explode).toMatchObject({ name: 'execute_tool explode', parent_span_id: main.span_id, status: 'error' });
182+
expect(read).toMatchObject({
183+
name: 'execute_tool read',
184+
parent_span_id: main.span_id,
185+
status: 'ok',
186+
attributes: expect.objectContaining({
187+
[GEN_AI_TOOL_CALL_ID_ATTRIBUTE]: { type: 'string', value: 'sevt_read' },
188+
}),
189+
});
190+
expect(receivedEvent).toMatchObject({
191+
exception: {
192+
values: [{ value: 'Tool exploded', mechanism: { type: 'auto.ai.anthropic', handled: true } }],
193+
},
194+
});
195+
});
196+
},
197+
{
198+
additionalDependencies: {
199+
'@anthropic-ai/sdk': '0.129.0',
200+
},
201+
},
202+
);
140203
});

‎packages/server-utils/src/ai/anthropic-ai/index.ts‎

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ import {
2727
} from '../core/utils';
2828
import { ANTHROPIC_AI_ORIGIN, ANTHROPIC_METHOD_REGISTRY } from './constants';
2929
import { instrumentAsyncIterableStream, instrumentMessageStream } from './streaming';
30-
import { instrumentToolRunnerMethod } from './tool-runner';
30+
import { instrumentSessionToolRunner, instrumentToolRunner, instrumentToolRunnerFactory } from './tool-runner';
3131
import type { AnthropicAiOptions, AnthropicAiResponse, AnthropicAiStreamingEvent, ContentBlock } from './types';
3232
import { handleResponseError, messagesFromParams, setMessagesAttribute } from './utils';
3333

@@ -351,9 +351,12 @@ function instrumentClientInPlace<T extends object>(client: T, options: Anthropic
351351
owner[methodName] = instrumented;
352352
}
353353

354-
const betaMessages = (client as { beta?: { messages?: object } }).beta?.messages;
355-
if (betaMessages) {
356-
instrumentToolRunnerMethod(betaMessages, options);
354+
const beta = (client as { beta?: { messages?: object; sessions?: { events?: object } } }).beta;
355+
if (beta?.messages) {
356+
instrumentToolRunnerFactory(beta.messages, instrumentToolRunner, options);
357+
}
358+
if (beta?.sessions?.events) {
359+
instrumentToolRunnerFactory(beta.sessions.events, instrumentSessionToolRunner, options);
357360
}
358361

359362
return client;

‎packages/server-utils/src/ai/anthropic-ai/tool-runner.ts‎

Lines changed: 19 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -26,12 +26,17 @@ type AnyFunction = (...args: unknown[]) => unknown;
2626
type RunnableTool = { name: string; description?: unknown };
2727
type RunContext = { toolUse?: { id?: unknown }; toolUseBlock?: { id?: unknown }; signal?: AbortSignal } | undefined;
2828
type ToolRunner = { params?: { tools?: unknown } };
29+
type SessionToolRunner = { tools?: unknown };
2930

30-
/** Wrap `beta.messages.toolRunner()` so the runners it returns trace their tool calls. */
31-
export function instrumentToolRunnerMethod(messages: object, options: AnthropicAiOptions): void {
32-
wrapInPlace(messages, 'toolRunner', (toolRunner, thisArg, args) => {
31+
/** Wrap the `toolRunner()` method of `owner` so the runners it returns trace their tool calls. */
32+
export function instrumentToolRunnerFactory(
33+
owner: object,
34+
instrumentRunner: (runner: unknown, options: AnthropicAiOptions) => void,
35+
options: AnthropicAiOptions,
36+
): void {
37+
wrapInPlace(owner, 'toolRunner', (toolRunner, thisArg, args) => {
3338
const runner = toolRunner.apply(thisArg, args);
34-
instrumentToolRunner(runner, options);
39+
instrumentRunner(runner, options);
3540
return runner;
3641
});
3742
}
@@ -56,6 +61,16 @@ export function instrumentToolRunner(runner: unknown, options: AnthropicAiOption
5661
});
5762
}
5863

64+
/** Give each tool call of a Managed Agents session runner a `gen_ai.execute_tool` span. */
65+
export function instrumentSessionToolRunner(runner: unknown, options: AnthropicAiOptions): void {
66+
if (!runner || typeof runner !== 'object') {
67+
return;
68+
}
69+
70+
// The session runner has no `addTools()`: it only runs the tools it was created with.
71+
instrumentTools((runner as SessionToolRunner).tools, options);
72+
}
73+
5974
function instrumentTools(tools: unknown, options: AnthropicAiOptions): void {
6075
if (!Array.isArray(tools)) {
6176
return;

‎packages/server-utils/src/integrations/anthropic.ts‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ import { wrapApiPromiseResponse } from '../ai/core/apiPromise';
1414
import { addPrivateRequestAttributes, addResponseAttributes, extractRequestAttributes } from '../ai/anthropic-ai';
1515
import { ANTHROPIC_AI_ORIGIN } from '../ai/anthropic-ai/constants';
1616
import { instrumentAsyncIterableStream, instrumentMessageStream } from '../ai/anthropic-ai/streaming';
17-
import { instrumentToolRunner } from '../ai/anthropic-ai/tool-runner';
17+
import { instrumentSessionToolRunner, instrumentToolRunner } from '../ai/anthropic-ai/tool-runner';
1818
import type { AnthropicAiOptions, AnthropicAiResponse } from '../ai/anthropic-ai/types';
1919
import type { OrchestrionChannelContext } from '../orchestrion/types';
2020
import { CHANNELS } from '../orchestrion/channels';
@@ -80,6 +80,11 @@ function instrumentAnthropic(options: AnthropicAiOptions): void {
8080
.end.subscribe(message => {
8181
instrumentToolRunner((message as OrchestrionChannelContext).result, options);
8282
});
83+
diagnosticsChannel
84+
.tracingChannel<OrchestrionChannelContext>(CHANNELS.ANTHROPIC_SESSION_TOOL_RUNNER)
85+
.end.subscribe(message => {
86+
instrumentSessionToolRunner((message as OrchestrionChannelContext).self, options);
87+
});
8388
}
8489

8590
/**

‎packages/server-utils/src/orchestrion/config/anthropic-ai.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,12 @@ export const anthropicAiConfig = [
3131
module: { name: '@anthropic-ai/sdk', versionRange: '>=0.63.0 <1', filePath },
3232
functionQuery: { className: 'Messages', methodName: 'toolRunner', kind: 'Sync' as const },
3333
})),
34+
// The constructor, not `sessions.events.toolRunner()`, so runners built directly (e.g. by `EnvironmentWorker`) are covered.
35+
...['lib/tools/SessionToolRunner.js', 'lib/tools/SessionToolRunner.mjs'].map(filePath => ({
36+
channelName: 'session-tool-runner',
37+
module: { name: '@anthropic-ai/sdk', versionRange: '>=0.97.0 <1', filePath },
38+
functionQuery: { className: 'SessionToolRunner' },
39+
})),
3440
] satisfies InstrumentationConfig[];
3541

3642
export const anthropicAiModuleNames = getModuleNames(anthropicAiConfig);
@@ -39,4 +45,5 @@ export const anthropicAiChannels = {
3945
ANTHROPIC_CHAT: 'orchestrion:@anthropic-ai/sdk:chat',
4046
ANTHROPIC_MESSAGES_STREAM: 'orchestrion:@anthropic-ai/sdk:messages-stream',
4147
ANTHROPIC_TOOL_RUNNER: 'orchestrion:@anthropic-ai/sdk:tool-runner',
48+
ANTHROPIC_SESSION_TOOL_RUNNER: 'orchestrion:@anthropic-ai/sdk:session-tool-runner',
4249
} as const;

‎packages/server-utils/test/ai/lib/tracing/anthropic-ai-tool-runner.test.ts‎

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,9 +32,31 @@ class FakeRunner {
3232
}
3333
}
3434

35+
// Mirrors the SDK session runner: it keeps `opts.tools` as `tools` and passes the call event as both `toolUse` and `toolUseBlock`.
36+
class FakeSessionRunner {
37+
public readonly tools: Tool[];
38+
public constructor(opts: { tools: Tool[] }) {
39+
this.tools = opts.tools;
40+
}
41+
public async dispatch(name: string, toolUse: { id: string; input: unknown }): Promise<{ isError: boolean }> {
42+
const tool = this.tools.find(t => t.name === name)!;
43+
try {
44+
await tool.run(toolUse.input, { toolUse, toolUseBlock: toolUse, signal: new AbortController().signal });
45+
return { isError: false };
46+
} catch {
47+
return { isError: true };
48+
}
49+
}
50+
}
51+
3552
function fakeClient() {
3653
return {
3754
beta: {
55+
sessions: {
56+
events: {
57+
toolRunner: vi.fn((_sessionId: string, opts: { tools: Tool[] }) => new FakeSessionRunner(opts)),
58+
},
59+
},
3860
messages: {
3961
create: vi.fn(),
4062
toolRunner: vi.fn((params: Params) => {
@@ -263,4 +285,50 @@ describe('instrumentAnthropicAiClient tool runner', () => {
263285

264286
expect(() => instrumented.beta.messages.toolRunner(undefined as unknown as Params)).toThrow('params required');
265287
});
288+
289+
describe('sessions.events.toolRunner()', () => {
290+
it('wraps each tool call of the session runner in an execute_tool span', async () => {
291+
const weather = tool('weather', async () => 'sunny');
292+
293+
const runner = instrumentAnthropicAiClient(fakeClient()).beta.sessions.events.toolRunner('sesn_1', {
294+
tools: [weather],
295+
});
296+
const parent = await startSpan({ name: 'agent' }, async span => {
297+
await runner.dispatch('weather', { id: 'sevt_1', input: { city: 'Vienna' } });
298+
return spanToStaticSpanJSON(span);
299+
});
300+
301+
expect(toolSpans()).toEqual([
302+
expect.objectContaining({
303+
description: 'execute_tool weather',
304+
parent_span_id: parent.span_id,
305+
origin: 'auto.ai.anthropic',
306+
status: 'ok',
307+
data: expect.objectContaining({
308+
[GEN_AI_TOOL_NAME]: 'weather',
309+
[GEN_AI_TOOL_CALL_ID_ATTRIBUTE]: 'sevt_1',
310+
}),
311+
}),
312+
]);
313+
});
314+
315+
it('captures the error of a failing tool, which the session runner turns into a result', async () => {
316+
const explode = tool('explode', async () => {
317+
throw new Error('disk full');
318+
});
319+
320+
const runner = instrumentAnthropicAiClient(fakeClient()).beta.sessions.events.toolRunner('sesn_1', {
321+
tools: [explode],
322+
});
323+
const outcome = await runner.dispatch('explode', { id: 'sevt_2', input: {} });
324+
325+
expect(outcome).toEqual({ isError: true });
326+
expect(toolSpans()[0]!.status).toBe('internal_error');
327+
await vi.waitFor(() => expect(events).toHaveLength(1));
328+
expect(events[0]!.exception?.values?.[0]).toMatchObject({
329+
value: 'disk full',
330+
mechanism: { type: 'auto.ai.anthropic', handled: true },
331+
});
332+
});
333+
});
266334
});

0 commit comments

Comments
 (0)