-
-
Notifications
You must be signed in to change notification settings - Fork 256
Expand file tree
/
Copy pathcli-tool-catalog.ts
More file actions
189 lines (168 loc) · 6.03 KB
/
cli-tool-catalog.ts
File metadata and controls
189 lines (168 loc) · 6.03 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
import type { ToolAnnotations } from '@modelcontextprotocol/sdk/types.js';
import type { ToolSchemaShape } from '../core/plugin-types.ts';
import { startDaemonBackground } from './daemon-control.ts';
import { DaemonClient } from './daemon-client.ts';
import { buildCliToolCatalogFromManifest, createToolCatalog } from '../runtime/tool-catalog.ts';
import type { ToolCatalog, ToolDefinition } from '../runtime/types.ts';
import { toKebabCase } from '../runtime/naming.ts';
import type { ToolHandlerContext } from '../rendering/types.ts';
import type { PipelineEvent } from '../types/pipeline-events.ts';
import { jsonSchemaToZod } from '../integrations/xcode-tools-bridge/jsonschema-to-zod.ts';
import { XcodeIdeToolService } from '../integrations/xcode-tools-bridge/tool-service.ts';
import { toLocalToolName } from '../integrations/xcode-tools-bridge/registry.ts';
import { log } from '../utils/logging/index.ts';
import { statusLine } from '../utils/tool-event-builders.ts';
interface BuildCliToolCatalogOptions {
socketPath: string;
workspaceRoot: string;
cliExposedWorkflowIds: string[];
discoveryMode?: 'none' | 'quick';
}
type JsonSchemaObject = {
properties?: Record<string, unknown>;
required?: unknown[];
};
function jsonSchemaToToolSchemaShape(inputSchema: unknown): ToolSchemaShape {
if (!inputSchema || typeof inputSchema !== 'object') {
return {};
}
const schema = inputSchema as JsonSchemaObject;
const properties = schema.properties;
if (!properties || typeof properties !== 'object' || Array.isArray(properties)) {
return {};
}
const requiredFields = new Set(
Array.isArray(schema.required)
? schema.required.filter((name): name is string => typeof name === 'string')
: [],
);
const shape: ToolSchemaShape = {};
for (const [name, propertySchema] of Object.entries(properties)) {
const zodSchema = jsonSchemaToZod(propertySchema);
shape[name] = requiredFields.has(name) ? zodSchema : zodSchema.optional();
}
return shape;
}
async function invokeRemoteToolOneShot(
remoteToolName: string,
args: Record<string, unknown>,
ctx: ToolHandlerContext,
): Promise<void> {
const service = new XcodeIdeToolService();
service.setWorkflowEnabled(true);
try {
const response = (await service.invokeTool(remoteToolName, args)) as unknown as {
content?: Array<{ type: string; text: string }>;
isError?: boolean;
_meta?: Record<string, unknown>;
};
const events = response._meta?.events;
if (Array.isArray(events)) {
for (const event of events as PipelineEvent[]) {
ctx.emit(event);
}
} else if (response.content) {
for (const item of response.content) {
if (item.type === 'text') {
ctx.emit(statusLine(response.isError ? 'error' : 'success', item.text));
}
}
}
} finally {
await service.disconnect();
}
}
type DynamicBridgeTool = {
name: string;
description?: string;
inputSchema?: unknown;
annotations?: ToolAnnotations;
};
function createCliXcodeProxyTool(remoteTool: DynamicBridgeTool): ToolDefinition {
const cliSchema = jsonSchemaToToolSchemaShape(remoteTool.inputSchema);
return {
cliName: toKebabCase(remoteTool.name),
mcpName: toLocalToolName(remoteTool.name),
workflow: 'xcode-ide',
description: remoteTool.description ?? '',
annotations: remoteTool.annotations,
mcpSchema: cliSchema,
cliSchema,
stateful: false,
xcodeIdeRemoteToolName: remoteTool.name,
handler: async (params, ctx): Promise<void> => {
return invokeRemoteToolOneShot(remoteTool.name, params, ctx);
},
};
}
async function loadDaemonBackedXcodeProxyTools(
opts: BuildCliToolCatalogOptions,
): Promise<ToolDefinition[]> {
const discoveryMode = opts.discoveryMode ?? 'none';
const quickMode = discoveryMode === 'quick';
const daemonClient = new DaemonClient({
socketPath: opts.socketPath,
timeout: quickMode ? 400 : 250,
});
try {
const isRunning = await daemonClient.isRunning();
if (!isRunning) {
if (!quickMode) {
return [];
}
// Fast path for CLI help/discovery: fire-and-forget daemon startup to avoid
// blocking command rendering while still warming a long-lived bridge session.
try {
startDaemonBackground({
socketPath: opts.socketPath,
workspaceRoot: opts.workspaceRoot,
});
} catch (startError) {
const message = startError instanceof Error ? startError.message : String(startError);
log('warn', `[xcode-ide] Failed to start daemon in background: ${message}`);
}
return [];
}
const tools = await daemonClient.listXcodeIdeTools({
refresh: false,
prefetch: quickMode,
});
return tools.map(
(tool): ToolDefinition =>
createCliXcodeProxyTool({
name: tool.remoteName,
description: tool.description,
inputSchema: tool.inputSchema,
annotations: tool.annotations,
}),
);
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
if (quickMode) {
log('warn', `[xcode-ide] CLI daemon-backed bridge discovery failed: ${message}`);
} else {
log('debug', `[xcode-ide] CLI cached bridge discovery skipped: ${message}`);
}
return [];
}
}
/**
* Build a tool catalog for CLI usage using the manifest system.
* CLI visibility is determined by manifest availability and predicates.
*/
export async function buildCliToolCatalog(opts: BuildCliToolCatalogOptions): Promise<ToolCatalog> {
const manifestCatalog = await buildCliToolCatalogFromManifest();
if (!opts.cliExposedWorkflowIds.includes('xcode-ide')) {
return manifestCatalog;
}
const dynamicTools = await loadDaemonBackedXcodeProxyTools(opts);
if (dynamicTools.length === 0) {
return manifestCatalog;
}
const existingCliNames = new Set(manifestCatalog.tools.map((tool) => tool.cliName));
const mergedTools = [
...manifestCatalog.tools,
...dynamicTools.filter((tool) => !existingCliNames.has(tool.cliName)),
];
return createToolCatalog(mergedTools);
}