Skip to content

Commit d78be6c

Browse files
thymikeeclaude
andauthored
feat(mcp)!: preload loop tools, trim schemas, and shorten errors (#4507)
* feat(mcp)!: preload loop tools, trim schemas, and shorten errors Claude Code defers MCP tool schemas, so each tool a run needs costs a tool search turn. Mark the 'loop' framework tier (open, snapshot, press, fill, back, wait, scroll, screenshot) with _meta "anthropic/alwaysLoad", and give every tool an "anthropic/searchHint" from its command text. Make the always-loaded schemas lean: debug, the MCP response controls (cost, responseLevel), and the target alias leave every tool schema. The controls become operator settings (AGENT_DEVICE_COST, AGENT_DEVICE_RESPONSE_LEVEL); mcpOutputFormat is removed. Loop tool descriptions carry their usage guidance from the command help text, batch documents its step shape with tested examples, MCP errors put the typed reason beside the code and drop the log path unless the recovery step reads it, and MCP open text drops the Session state path. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(mcp): restore caller-facing contract facts and type the log-path rule - Settle fields state the diff is against the pre-action tree and keep the iOS 300 ms default and broad-replacement floor, tersely. - open documents initialSnapshotError on a fresh open; customActions keeps its recovery routes, with the full wording in help snapshot. - Model-facing errors keep the log path only when the code's default step reads the log (defaultHintReadsLog), and bound details.reason to one line. - batch grounds its @E12 example; searchHints carry only words the tool text lacks, enforced by a test. Co-Authored-By: Claude Opus 5.5 <[email protected]> * test(mcp): assert the INVALID_ARGS error before checking the log path is absent Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(batch): derive the MCP batch deadline from its timeout policy Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(ai-sdk): keep tier-less commands out of the core tool set Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(mcp): keep the diagnostics log path and full message in agent error text A producer hint that sends the reader to the runner or diagnostics log lost the path under the default-hint rule. Agent text now keeps the Log: line whenever a log exists and the full Message: line when the summary cuts it. Co-Authored-By: Claude Opus 5.5 <[email protected]> * docs(ai-sdk): note the pinned session and platform in tool arguments Co-Authored-By: Claude Opus 5.5 <[email protected]> * docs: say which AI SDK fields are refused and that errors include the log path Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(mcp): stop preloading screenshot Benchmark runs showed that a preloaded screenshot pulls agents into a screenshot, image read and coordinate-tap detour whenever open returns before the app is ready, so it moves back to the core tier: still in the default AI SDK set, loaded on demand over MCP. Co-Authored-By: Claude Opus 5.5 <[email protected]> * test: drop screenshot from the pinned loop tier set Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(mcp): keep reinstall's search keywords out of its description; format the loop pin Co-Authored-By: Claude Opus 5.5 <[email protected]> * docs(mcp): screenshot is no longer always loaded Co-Authored-By: Claude Opus 5.5 <[email protected]> --------- Co-authored-by: Claude Opus 5.5 <[email protected]>
1 parent 7c55c02 commit d78be6c

60 files changed

Lines changed: 551 additions & 192 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎packages/command-output/src/cli-output.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,7 @@ export async function dispatchCliOutput(
7676
progress: params.progress,
7777
env: params.env,
7878
stderrIsTTY: params.stderrIsTTY,
79+
reader: params.reader,
7980
});
8081
if (output === undefined) return undefined;
8182
return routeResponseWarnings(

‎packages/command-output/src/management/output.test.ts‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,22 @@ describe('openCliOutput', () => {
2222
});
2323
});
2424

25+
test('leaves the session state directory out of the text a model reads', async () => {
26+
const output = await openCliOutput(
27+
{
28+
session: 'default',
29+
sessionStateDir: '/tmp/agent-device/sessions/cwd_123_default',
30+
identifiers: { session: 'default' },
31+
},
32+
'model',
33+
);
34+
35+
expect(output.text).toBe('Opened: default');
36+
expect(output.data).toMatchObject({
37+
sessionStateDir: '/tmp/agent-device/sessions/cwd_123_default',
38+
});
39+
});
40+
2541
test('keeps internal open timing out of public output data', async () => {
2642
const result: AppOpenResult & { timing: { totalDurationMs: number } } = {
2743
session: 'default',

‎packages/command-output/src/management/output.ts‎

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ import { readCommandMessage } from '@agent-device/kernel/success-text';
2222
import { snapshotCliOutput } from '../capture/output.ts';
2323
import {
2424
type CliOutputFormatter,
25+
type CliOutputFormatterParams,
2526
messageCliOutput,
2627
messageOutput,
2728
resultOutput,
@@ -87,11 +88,14 @@ async function sessionCliOutput(
8788
return { data, text: JSON.stringify(data, null, 2) };
8889
}
8990

90-
export async function openCliOutput(result: AppOpenResult): Promise<CliOutput> {
91+
export async function openCliOutput(
92+
result: AppOpenResult,
93+
reader: CliOutputFormatterParams['reader'] = 'terminal',
94+
): Promise<CliOutput> {
9195
const { serializeOpenResult } = await import('../output/result-serialization.ts');
9296
const data = serializeOpenResult(result);
9397
const lines = [readCommandMessage(data)].filter((line): line is string => Boolean(line));
94-
if (typeof data.sessionStateDir === 'string') {
98+
if (reader === 'terminal' && typeof data.sessionStateDir === 'string') {
9599
lines.push(`Session state: ${data.sessionStateDir}`);
96100
}
97101
for (const warning of result.warnings ?? []) {
@@ -243,7 +247,7 @@ export const managementCliOutputFormatters = {
243247
}),
244248
session: resultOutput(sessionCliOutput),
245249
artifacts: resultOutput(artifactsCliOutput),
246-
open: resultOutput(openCliOutput),
250+
open: ({ result, reader }) => openCliOutput(result as AppOpenResult, reader),
247251
close: resultOutput(closeCliOutput),
248252
install: resultOutput(deployCliOutput),
249253
reinstall: resultOutput(deployCliOutput),

‎packages/command-output/src/output-common.ts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,8 +38,16 @@ export type CliOutputFormatterParams = {
3838
env: EnvMap;
3939
/** Whether the caller's stderr is a terminal; a formatter that colors status markers reads it. */
4040
stderrIsTTY: boolean;
41+
/**
42+
* Who reads the text. `terminal` (the default) is a person or script at the CLI. `model` is
43+
* an agent reading a tool result, which gets no daemon-host state paths it would never open.
44+
*/
45+
reader?: OutputReader;
4146
};
4247

48+
/** Who reads command output: a person or script at the CLI, or an agent reading a tool result. */
49+
export type OutputReader = 'terminal' | 'model';
50+
4351
export type CliOutputFormatter = (
4452
params: CliOutputFormatterParams,
4553
) => CliOutput | Promise<CliOutput>;

‎packages/command-output/src/output/error.ts‎

Lines changed: 34 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import {
88
type NormalizedError,
99
} from '@agent-device/kernel/errors';
1010
import { readResponseWarnings } from '@agent-device/kernel/success-text';
11+
import type { OutputReader } from '../output-common.ts';
1112
import { formatReplayDivergenceReport } from '@agent-device/ad-replay/divergence';
1213
import { collapseWarningText } from '../output-common.ts';
1314

@@ -25,6 +26,12 @@ export type HumanErrorView = {
2526
export type HumanErrorOptions = {
2627
/** Append the raw details dump (the `--debug` tier). */
2728
showDetails?: boolean;
29+
/**
30+
* Who reads the text. `terminal` (the default) is a person or script at the CLI. `model` is
31+
* an agent reading a tool result: the typed `details.reason` joins the code and the summary
32+
* stays one line.
33+
*/
34+
reader?: OutputReader;
2835
/** The failing command's synopsis, such as `agent-device fill <target> <text>`. */
2936
synopsis?: string;
3037
};
@@ -48,7 +55,13 @@ export function formatHumanError(
4855
const candidateViews = readErrorCandidateViews(normalized.details);
4956
const inlineCandidates =
5057
normalized.code === 'AMBIGUOUS_MATCH' ? readInlineCandidates(candidateViews) : undefined;
51-
const { summary, truncated } = formatSummary(normalized, inlineCandidates, options.synopsis);
58+
const forModel = options.reader === 'model';
59+
const { summary, truncated } = formatSummary(
60+
normalized,
61+
inlineCandidates,
62+
options.synopsis,
63+
forModel,
64+
);
5265
return {
5366
summary,
5467
body: formatBody(normalized, {
@@ -63,6 +76,7 @@ function formatSummary(
6376
normalized: NormalizedError,
6477
inlineCandidates: string[] | undefined,
6578
synopsis: string | undefined,
79+
withReason: boolean,
6680
): { summary: string; truncated: boolean } {
6781
const dispatched = readDispatchDisclosure(normalized.details);
6882
const message = oneLine(normalized.message);
@@ -71,8 +85,10 @@ function formatSummary(
7185
? `${message.slice(0, SUMMARY_MESSAGE_LIMIT)}…`
7286
: message;
7387
const next = nextStep(normalized, dispatched, inlineCandidates, synopsis);
88+
const reason = withReason ? readReason(normalized) : undefined;
89+
const label = reason ? `${normalized.code}, ${reason}` : normalized.code;
7490
const summary = [
75-
`Error (${normalized.code}): ${withFullStop(shown)}`,
91+
`Error (${label}): ${withFullStop(shown)}`,
7692
...(dispatched ? [DISPATCH_SENTENCE[dispatched]] : []),
7793
...(next ? [`Next: ${next}`] : []),
7894
].join(' ');
@@ -106,9 +122,24 @@ function nextStep(
106122
return parts.length > 0 ? parts.join(' ') : undefined;
107123
}
108124

125+
const REASON_LIMIT = 80;
126+
127+
/** The typed `details.reason`, when the throw site classified the failure, as one bounded line. */
128+
function readReason(normalized: NormalizedError): string | undefined {
129+
const raw = normalized.details?.reason;
130+
if (typeof raw !== 'string') return undefined;
131+
const reason = oneLine(raw);
132+
if (reason.length === 0) return undefined;
133+
return reason.length > REASON_LIMIT ? `${reason.slice(0, REASON_LIMIT)}…` : reason;
134+
}
135+
109136
function formatBody(
110137
normalized: NormalizedError,
111-
options: { fullMessage: boolean; candidateViews: ErrorCandidateView[]; showDetails?: boolean },
138+
options: {
139+
fullMessage: boolean;
140+
candidateViews: ErrorCandidateView[];
141+
showDetails?: boolean;
142+
},
112143
): string[] {
113144
const body: string[] = [];
114145
if (options.fullMessage) body.push(`Message: ${normalized.message}`);

‎packages/command-registry/src/command-text.ts‎

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,11 +8,13 @@
88
* description what does it do, and when should I reach for it?
99
* cliDetail what else does a terminal user need — flags, argument shapes, examples?
1010
* mcpDetail what else does an MCP caller need about this command's behavior?
11+
* searchHint which words would a model searching for this tool type that the text lacks?
1112
*
1213
* `--help`, the command list, the MCP tool description and `explain` are all projections of
13-
* these four, computed where they are rendered rather than written back into the schema. That
14+
* the first four, computed where they are rendered rather than written back into the schema. That
1415
* is deliberate: the field this replaced was authored on some commands and generated on others,
15-
* which is how surfaces silently drifted apart.
16+
* which is how surfaces silently drifted apart. `searchHint` renders nowhere in that text; it
17+
* goes only to the MCP tool's `_meta`.
1618
*
1719
* Because `cliDetail` is the only field carrying terminal vocabulary, and the MCP surface never
1820
* reads it, MCP descriptions stay free of flags and positional syntax structurally rather than
@@ -27,14 +29,22 @@ export type CommandText = {
2729
cliDetail?: string;
2830
/** Appended to the MCP tool description only: command behavior and input details. */
2931
mcpDetail?: string;
32+
/**
33+
* Space-separated keywords a client's deferred-tool search matches besides the name and
34+
* description: synonyms and task words a model types, such as "tap button" for press.
35+
* Every MCP tool declares one; CLI-only commands need none.
36+
*/
37+
searchHint?: string;
3038
};
3139

3240
/**
3341
* What a command backed by a family facet authors. `description` is absent because the facet's
3442
* metadata already carries it — repeating it here would leave a shadowed copy behind, which is
3543
* exactly the dead-literal problem this file's predecessor had.
3644
*/
37-
export type FacetCommandText = Omit<CommandText, 'description'>;
45+
export type FacetCommandText = Omit<CommandText, 'description' | 'searchHint'> & {
46+
searchHint: string;
47+
};
3848

3949
/** The `--help` body: canonical description plus any terminal-only detail. */
4050
export function helpBody(text: CommandText): string {
@@ -47,7 +57,10 @@ export function mcpBody(text: Pick<CommandText, 'description' | 'mcpDetail'>): s
4757
}
4858

4959
/** Resolves a facet's authored text against the description its metadata already holds. */
50-
export function resolveFacetText(text: FacetCommandText, description: string): CommandText {
60+
export function resolveFacetText(
61+
text: FacetCommandText,
62+
description: string,
63+
): CommandText & FacetCommandText {
5164
return { ...text, description };
5265
}
5366

‎packages/command-registry/src/descriptors/device-operations.ts‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,7 @@ export const DEVICE_OPERATION_COMMAND_DESCRIPTORS = {
6767
? { ownerFiles: ['packages/command-surface/src/capture/wait.ts'] as const }
6868
: {}),
6969
catalog: { group: 'public' },
70-
frameworkTier: 'core',
70+
frameworkTier: 'loop',
7171
recordsSessionAction: true,
7272
recordingEffect: 'observes-app',
7373
// #1349: a wait's landmark may legitimately be absent when the step
@@ -253,7 +253,7 @@ export const DEVICE_OPERATION_COMMAND_DESCRIPTORS = {
253253
: {}),
254254
...TARGETED_TOUCH_INTERACTION_TRAITS,
255255
daemon: { ...TARGETED_TOUCH_INTERACTION_TRAITS.daemon, appLease: 'allowed' },
256-
frameworkTier: 'core',
256+
frameworkTier: 'loop',
257257
timeoutPolicy: postActionObservationTimeoutPolicy('fill', PRESERVE_DAEMON_TIMEOUT_POLICY),
258258
postActionObservation: postActionObservation('fill'),
259259
responseDataTransform: FILL_INTERACTION_RESPONSE_DATA_TRANSFORM,
@@ -309,7 +309,7 @@ export const DEVICE_OPERATION_COMMAND_DESCRIPTORS = {
309309
: {}),
310310
...TARGETED_TOUCH_INTERACTION_TRAITS,
311311
daemon: { ...TARGETED_TOUCH_INTERACTION_TRAITS.daemon, appLease: 'allowed' },
312-
frameworkTier: 'core',
312+
frameworkTier: 'loop',
313313
timeoutPolicy: postActionObservationTimeoutPolicy('press', PRESERVE_DAEMON_TIMEOUT_POLICY),
314314
postActionObservation: postActionObservation('press'),
315315
responseDataTransform: TOUCH_INTERACTION_RESPONSE_DATA_TRANSFORM,
@@ -380,7 +380,7 @@ export const DEVICE_OPERATION_COMMAND_DESCRIPTORS = {
380380
? { ownerFiles: ['packages/command-surface/src/system/index.ts'] as const }
381381
: {}),
382382
catalog: { group: 'public' },
383-
frameworkTier: 'core',
383+
frameworkTier: 'loop',
384384
// R42 retires this command's capability bucket and its `dispatch` leaf together: admission is
385385
// the owner's `back` fact, and the only execution is the bound operation — the postActionObservation
386386
// timeout trait it kept is admission-independent, like `type` kept its dialog guard.
@@ -483,7 +483,7 @@ export const DEVICE_OPERATION_COMMAND_DESCRIPTORS = {
483483
? { ownerFiles: ['packages/daemon/src/execution/scroll-runtime.ts'] as const }
484484
: {}),
485485
catalog: { group: 'public' },
486-
frameworkTier: 'core',
486+
frameworkTier: 'loop',
487487
// R53 retires this command's capability bucket and its `dispatch` leaf together: admission is
488488
// the owner's `scrollDirection` fact, and the only execution is the bound operation. `scroll`
489489
// was the last holder of the legacy `dispatch`/`capability` pair, which retires with it.

‎packages/command-registry/src/descriptors/session-operations.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -385,7 +385,7 @@ export const SESSION_OPERATION_COMMAND_DESCRIPTORS = [
385385
? { ownerFiles: ['packages/command-surface/src/management/app.ts'] as const }
386386
: {}),
387387
catalog: { group: 'public' },
388-
frameworkTier: 'core',
388+
frameworkTier: 'loop',
389389
recordsSessionAction: true,
390390
recordingEffect: 'mutates-app',
391391
daemon: {

‎packages/command-registry/src/flag-definitions-workflow.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -269,7 +269,7 @@ export const WORKFLOW_FLAG_DEFINITIONS: readonly FlagDefinition[] = [
269269
usageDescription:
270270
'Snapshot: name the affordances merged inside an element (iOS sim); not directly invokable — reach them via the detail screen, labeled children, or coordinates',
271271
inputDescription:
272-
'Name the affordances an element merged away (iOS UIAccessibilityCustomAction, React Native accessibilityActions) — a card whose reply/options controls are not separate elements still lists them here. The names are for PLANNING, not invocation: there is no API to trigger them, so reach the affordance through the element detail screen, through the same control exposed as a labeled element elsewhere, or by coordinates from its rect. iOS simulator only; costs one accessibility round trip per merged element.',
272+
"List the custom actions an element merged away, such as a card's reply control. Not invocable: reach the control via its detail screen, a labeled element elsewhere, or its rect. iOS simulator only; costs one accessibility round trip per merged element.",
273273
projectConfig: true,
274274
recorded: true,
275275
},

‎packages/command-registry/src/registry.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -443,7 +443,7 @@ export const RAW_COMMAND_DESCRIPTORS = [
443443
? { ownerFiles: ['packages/command-surface/src/capture/snapshot.ts'] as const }
444444
: {}),
445445
catalog: { group: 'public' },
446-
frameworkTier: 'core',
446+
frameworkTier: 'loop',
447447
recordsSessionAction: true,
448448
recordingEffect: 'observes-app',
449449
daemon: { route: 'snapshot', refFrameEffect: 'preserve', appLease: 'allowed' },
@@ -809,7 +809,7 @@ export function resolveCommandRecordsSessionAction(command: string | undefined):
809809
* `undefined` for a command that never declares one. A tier is declared iff
810810
* `catalog.group === 'public'`; that rule is a runtime pin, not a type rule —
811811
* `src/__tests__/command-descriptor-parity.test.ts` asserts it and the exact
812-
* `'core'` tool set, so a new public command cannot join a framework adapter's
812+
* `'loop'` and `'core'` tool sets, so a new public command cannot join a framework adapter's
813813
* default set silently. Framework adapters (`agent-device/ai-sdk`,
814814
* `@agent-device/eve`) read this to build their default tool set instead of
815815
* hand-listing tool names.

0 commit comments

Comments
 (0)