@abhishek944/pi-classifier 0.3.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/CHANGELOG.md +48 -0
  2. package/COMPUTER_USE.md +117 -0
  3. package/README.md +344 -30
  4. package/dist/auth.d.ts +4 -2
  5. package/dist/auth.js +18 -2
  6. package/dist/box-tool.d.ts +4 -0
  7. package/dist/box-tool.js +79 -0
  8. package/dist/box.d.ts +32 -0
  9. package/dist/box.js +148 -0
  10. package/dist/choices.js +35 -1
  11. package/dist/classify.d.ts +6 -0
  12. package/dist/classify.js +4 -4
  13. package/dist/computer-use-state.d.ts +9 -0
  14. package/dist/computer-use-state.js +160 -0
  15. package/dist/computer-use-tool.d.ts +52 -0
  16. package/dist/computer-use-tool.js +78 -0
  17. package/dist/computer-use-types.d.ts +132 -0
  18. package/dist/computer-use-types.js +1 -0
  19. package/dist/computer-use.d.ts +22 -0
  20. package/dist/computer-use.js +223 -0
  21. package/dist/config.d.ts +140 -3
  22. package/dist/config.js +405 -20
  23. package/dist/cost.js +42 -4
  24. package/dist/durable.d.ts +34 -0
  25. package/dist/durable.js +237 -0
  26. package/dist/extension.d.ts +2 -247
  27. package/dist/extension.js +53 -190
  28. package/dist/extract.d.ts +11 -0
  29. package/dist/extract.js +191 -0
  30. package/dist/http.d.ts +6 -1
  31. package/dist/http.js +64 -28
  32. package/dist/image-content.d.ts +12 -0
  33. package/dist/image-content.js +90 -0
  34. package/dist/index.d.ts +10 -1
  35. package/dist/index.js +3 -0
  36. package/dist/inputs.d.ts +24 -2
  37. package/dist/inputs.js +565 -134
  38. package/dist/mcp-cli.d.ts +2 -0
  39. package/dist/mcp-cli.js +39 -0
  40. package/dist/mcp-server.d.ts +28 -0
  41. package/dist/mcp-server.js +121 -0
  42. package/dist/mcp-tool-definitions.d.ts +19 -0
  43. package/dist/mcp-tool-definitions.js +64 -0
  44. package/dist/providers.d.ts +1 -0
  45. package/dist/providers.js +1218 -124
  46. package/dist/tool-contracts.d.ts +785 -0
  47. package/dist/tool-contracts.js +530 -0
  48. package/dist/tree.js +1 -1
  49. package/dist/types.d.ts +314 -20
  50. package/dist/validation.js +181 -44
  51. package/package.json +33 -5
  52. package/src/auth.ts +26 -2
  53. package/src/box-tool.ts +110 -0
  54. package/src/box.ts +253 -0
  55. package/src/choices.ts +44 -2
  56. package/src/classify.ts +10 -6
  57. package/src/computer-use-state.ts +145 -0
  58. package/src/computer-use-tool.ts +76 -0
  59. package/src/computer-use-types.ts +127 -0
  60. package/src/computer-use.ts +216 -0
  61. package/src/config.ts +454 -23
  62. package/src/cost.ts +42 -4
  63. package/src/durable.ts +298 -0
  64. package/src/extension.ts +79 -265
  65. package/src/extract.ts +228 -0
  66. package/src/http.ts +63 -32
  67. package/src/image-content.ts +77 -0
  68. package/src/index.ts +25 -0
  69. package/src/inputs.ts +603 -184
  70. package/src/mcp-cli.ts +44 -0
  71. package/src/mcp-server.ts +179 -0
  72. package/src/mcp-tool-definitions.ts +104 -0
  73. package/src/providers.ts +1398 -144
  74. package/src/tool-contracts.ts +785 -0
  75. package/src/tree.ts +1 -1
  76. package/src/types.ts +248 -11
  77. package/src/validation.ts +169 -96
package/src/mcp-cli.ts ADDED
@@ -0,0 +1,44 @@
1
+ #!/usr/bin/env node
2
+ // pi-classifier-mcp: serves the classifier tools over MCP stdio. stdout carries
3
+ // only JSON-RPC, so every diagnostic goes to stderr.
4
+
5
+ import { createRequire } from 'node:module';
6
+ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
7
+ import { createClassifierMcpServer } from './mcp-server.js';
8
+
9
+ const require = createRequire(import.meta.url);
10
+ const manifest: unknown = require('../package.json');
11
+ const version =
12
+ typeof manifest === 'object' && manifest !== null && 'version' in manifest && typeof manifest.version === 'string'
13
+ ? manifest.version
14
+ : '0.0.0';
15
+
16
+ // Keep stray dependency output off the JSON-RPC stream.
17
+ console.log = console.info = console.debug = console.error;
18
+
19
+ const server = createClassifierMcpServer({ cwd: process.cwd(), info: { name: 'pi-classifier', version } });
20
+ const transport = new StdioServerTransport();
21
+
22
+ let closing = false;
23
+ async function shutdown(code: number): Promise<void> {
24
+ if (closing) return;
25
+ closing = true;
26
+ try {
27
+ await server.close();
28
+ } catch (error) {
29
+ console.error('pi-classifier-mcp: error during shutdown:', error);
30
+ }
31
+ process.exit(code);
32
+ }
33
+
34
+ process.stdin.once('end', () => void shutdown(0));
35
+ process.stdin.once('close', () => void shutdown(0));
36
+ process.once('SIGINT', () => void shutdown(0));
37
+ process.once('SIGTERM', () => void shutdown(0));
38
+
39
+ try {
40
+ await server.connect(transport);
41
+ } catch (error) {
42
+ console.error('pi-classifier-mcp: failed to start:', error);
43
+ process.exit(1);
44
+ }
@@ -0,0 +1,179 @@
1
+ // Independent MCP server for the classifier package. Tool behavior stays in
2
+ // the owning package's core functions; this module only lists tools, validates
3
+ // arguments at the MCP boundary, forwards cancellation, and maps results to
4
+ // MCP content.
5
+
6
+ import { createRequire } from 'node:module';
7
+ import { Server } from '@modelcontextprotocol/sdk/server/index.js';
8
+ import {
9
+ CallToolRequestSchema,
10
+ ErrorCode,
11
+ ListToolsRequestSchema,
12
+ McpError,
13
+ type CallToolResult,
14
+ } from '@modelcontextprotocol/sdk/types.js';
15
+ import type { CredentialSource } from './auth.js';
16
+ import { renderClassifierBox } from './box.js';
17
+ import { classify, compareClassifiers } from './classify.js';
18
+ import { loadClassifierSettings } from './config.js';
19
+ import { extract } from './extract.js';
20
+ import {
21
+ CLASSIFIER_BOX_TOOL,
22
+ CLASSIFY_COMPARE_TOOL,
23
+ CLASSIFY_EXTRACT_TOOL,
24
+ CLASSIFY_TOOL,
25
+ CLASSIFY_TREE_TOOL,
26
+ } from './tool-contracts.js';
27
+ import { classifyTree } from './tree.js';
28
+ import { userError, type ClassifierSettings } from './types.js';
29
+ import {
30
+ CLASSIFIER_MCP_TOOL_DEFINITIONS,
31
+ validateMcpToolArguments,
32
+ type ClassifierMcpToolName,
33
+ } from './mcp-tool-definitions.js';
34
+
35
+ export interface McpServerInfo {
36
+ name: string;
37
+ version: string;
38
+ }
39
+
40
+ export interface ClassifierMcpServerOptions {
41
+ /** Directory for relative image, media, tree and output paths. Defaults to process.cwd(). */
42
+ cwd?: string;
43
+ /** Preloaded settings; otherwise read by the owning package. */
44
+ settings?: ClassifierSettings;
45
+ /** Project settings are not loaded unless the caller supplies trust explicitly. */
46
+ projectTrusted?: boolean;
47
+ /**
48
+ * Credential origin. The standalone server defaults to explicit provider keys
49
+ * so a non-Pi MCP client cannot silently use Pi chat login credentials.
50
+ */
51
+ credentialSource?: CredentialSource;
52
+ /** Optional allowlist of MCP tool names. */
53
+ enabledTools?: readonly ClassifierMcpToolName[];
54
+ info?: McpServerInfo;
55
+ }
56
+
57
+ const require = createRequire(import.meta.url);
58
+ const manifest: unknown = require('../package.json');
59
+ const packageVersion =
60
+ typeof manifest === 'object' && manifest !== null && 'version' in manifest && typeof manifest.version === 'string'
61
+ ? manifest.version
62
+ : '0.0.0';
63
+
64
+ export const classifierMcpServerInfo: McpServerInfo = {
65
+ name: 'pi-classifier',
66
+ version: packageVersion,
67
+ };
68
+
69
+ function errorResult(text: string): CallToolResult {
70
+ return { content: [{ type: 'text', text }], isError: true };
71
+ }
72
+
73
+ function jsonResult(value: object): CallToolResult {
74
+ return {
75
+ content: [{ type: 'text', text: JSON.stringify(value, null, 2) }],
76
+ structuredContent: { result: value },
77
+ };
78
+ }
79
+
80
+ /** Create an MCP Server. The CLI connects it to stdio; embedders own any other transport. */
81
+ export function createClassifierMcpServer(options: ClassifierMcpServerOptions = {}): Server {
82
+ const cwd = options.cwd ?? process.cwd();
83
+ const settings = options.settings ?? loadClassifierSettings(cwd, options.projectTrusted ?? false);
84
+ const credentialSource = options.credentialSource ?? 'explicit';
85
+ const enabled = options.enabledTools;
86
+ const tools = enabled === undefined
87
+ ? CLASSIFIER_MCP_TOOL_DEFINITIONS
88
+ : CLASSIFIER_MCP_TOOL_DEFINITIONS.filter((tool) => enabled.includes(tool.name));
89
+
90
+ const server = new Server(options.info ?? classifierMcpServerInfo, {
91
+ capabilities: { tools: {} },
92
+ instructions:
93
+ 'Independent pi-classifier MCP server. Provider routes and credentials stay on the server; relative paths resolve against the server process cwd. Classification and comparison calls may incur charges and send supplied state to the configured provider.',
94
+ });
95
+
96
+ server.setRequestHandler(ListToolsRequestSchema, async () => ({
97
+ tools: tools.map((tool) => ({
98
+ name: tool.name,
99
+ description: tool.description,
100
+ inputSchema: tool.inputSchema,
101
+ annotations: tool.annotations,
102
+ })),
103
+ }));
104
+
105
+ server.setRequestHandler(CallToolRequestSchema, async (request, extra) => {
106
+ const name = request.params.name;
107
+ const tool = tools.find((candidate) => candidate.name === name);
108
+ if (tool === undefined) throw new McpError(ErrorCode.InvalidParams, `Unknown tool: ${name}`);
109
+
110
+ const args = request.params.arguments ?? {};
111
+ const problems = validateMcpToolArguments(tool, args);
112
+ if (problems.length > 0) return errorResult(`Invalid arguments for ${name}:\n- ${problems.join('\n- ')}`);
113
+
114
+ const signal = extra.signal;
115
+ const requestOptions = {
116
+ settings,
117
+ cwd,
118
+ credentialSource,
119
+ ...(signal ? { signal } : {}),
120
+ };
121
+
122
+ try {
123
+ switch (tool.name) {
124
+ case CLASSIFY_TOOL:
125
+ return jsonResult(await classify(args, requestOptions));
126
+ case CLASSIFY_COMPARE_TOOL:
127
+ return jsonResult(await compareClassifiers(args, requestOptions));
128
+ case CLASSIFY_TREE_TOOL:
129
+ return jsonResult(await classifyTree(args, requestOptions));
130
+ case CLASSIFY_EXTRACT_TOOL:
131
+ return jsonResult(await extract(args, requestOptions));
132
+ case CLASSIFIER_BOX_TOOL: {
133
+ const result = await renderClassifierBox(args, {
134
+ cwd,
135
+ ...(signal ? { signal } : {}),
136
+ });
137
+ const byteLength = Buffer.from(result.data, 'base64').byteLength;
138
+ const details = {
139
+ mode: result.mode,
140
+ mimeType: result.mimeType,
141
+ width: result.width,
142
+ height: result.height,
143
+ pixelBox: result.pixelBox,
144
+ byteLength,
145
+ };
146
+ return {
147
+ content: [
148
+ {
149
+ type: 'text',
150
+ text:
151
+ `Rendered ${result.mode} box as a ${result.width}×${result.height} PNG ` +
152
+ `(${byteLength} bytes). Source pixel box: left=${result.pixelBox.left}, ` +
153
+ `top=${result.pixelBox.top}, width=${result.pixelBox.width}, ` +
154
+ `height=${result.pixelBox.height}. A box is a localization hint, not proof that the object exists.`,
155
+ },
156
+ { type: 'image', data: result.data, mimeType: result.mimeType },
157
+ ],
158
+ structuredContent: { result: details },
159
+ };
160
+ }
161
+ default: {
162
+ const exhaustive: never = tool.name;
163
+ return errorResult(`Unhandled tool: ${exhaustive}`);
164
+ }
165
+ }
166
+ } catch (error) {
167
+ return errorResult(`${tool.name} failed: ${userError(error)}`);
168
+ }
169
+ });
170
+
171
+ return server;
172
+ }
173
+
174
+ export {
175
+ CLASSIFIER_MCP_TOOL_DEFINITIONS,
176
+ validateMcpToolArguments,
177
+ type ClassifierMcpToolDefinition,
178
+ type ClassifierMcpToolName,
179
+ } from './mcp-tool-definitions.js';
@@ -0,0 +1,104 @@
1
+ // MCP-only catalog for the standalone stdio server. The argument schemas come
2
+ // from the package-owned tool contracts shared with the Pi extension and the
3
+ // Durable factory; this module only adapts them to MCP metadata and validation.
4
+
5
+ import { Value } from 'typebox/value';
6
+ import type { TSchema } from 'typebox';
7
+ import {
8
+ CLASSIFIER_BOX_TOOL,
9
+ CLASSIFIER_BOX_TOOL_DESCRIPTION,
10
+ CLASSIFY_COMPARE_TOOL,
11
+ CLASSIFY_COMPARE_TOOL_DESCRIPTION,
12
+ CLASSIFY_EXTRACT_TOOL,
13
+ CLASSIFY_EXTRACT_TOOL_DESCRIPTION,
14
+ CLASSIFY_TOOL,
15
+ CLASSIFY_TOOL_DESCRIPTION,
16
+ CLASSIFY_TREE_TOOL,
17
+ CLASSIFY_TREE_TOOL_DESCRIPTION,
18
+ boxParameters,
19
+ classifyExtractParameters,
20
+ classifyParameters,
21
+ classifyTreeParameters,
22
+ } from './tool-contracts.js';
23
+
24
+ export type ClassifierMcpToolName =
25
+ | typeof CLASSIFY_TOOL
26
+ | typeof CLASSIFY_COMPARE_TOOL
27
+ | typeof CLASSIFY_TREE_TOOL
28
+ | typeof CLASSIFY_EXTRACT_TOOL
29
+ | typeof CLASSIFIER_BOX_TOOL;
30
+
31
+ export interface ClassifierMcpToolAnnotations {
32
+ readOnlyHint: boolean;
33
+ destructiveHint: boolean;
34
+ idempotentHint?: boolean;
35
+ openWorldHint: boolean;
36
+ }
37
+
38
+ export interface ClassifierMcpToolDefinition {
39
+ name: ClassifierMcpToolName;
40
+ description: string;
41
+ inputSchema: TSchema;
42
+ annotations: ClassifierMcpToolAnnotations;
43
+ }
44
+
45
+ const providerAnnotations: ClassifierMcpToolAnnotations = {
46
+ readOnlyHint: true,
47
+ destructiveHint: false,
48
+ openWorldHint: true,
49
+ };
50
+
51
+ const localAnnotations: ClassifierMcpToolAnnotations = {
52
+ readOnlyHint: true,
53
+ destructiveHint: false,
54
+ openWorldHint: false,
55
+ };
56
+
57
+ /** Excludes Pi-only computer use; all portable package tools are exposed. */
58
+ export const CLASSIFIER_MCP_TOOL_DEFINITIONS: readonly ClassifierMcpToolDefinition[] = [
59
+ {
60
+ name: CLASSIFY_TOOL,
61
+ description: CLASSIFY_TOOL_DESCRIPTION,
62
+ inputSchema: classifyParameters,
63
+ annotations: providerAnnotations,
64
+ },
65
+ {
66
+ name: CLASSIFY_COMPARE_TOOL,
67
+ description: CLASSIFY_COMPARE_TOOL_DESCRIPTION,
68
+ inputSchema: classifyParameters,
69
+ annotations: providerAnnotations,
70
+ },
71
+ {
72
+ name: CLASSIFY_TREE_TOOL,
73
+ description: CLASSIFY_TREE_TOOL_DESCRIPTION,
74
+ inputSchema: classifyTreeParameters,
75
+ annotations: providerAnnotations,
76
+ },
77
+ {
78
+ name: CLASSIFY_EXTRACT_TOOL,
79
+ description: CLASSIFY_EXTRACT_TOOL_DESCRIPTION,
80
+ inputSchema: classifyExtractParameters,
81
+ annotations: providerAnnotations,
82
+ },
83
+ {
84
+ name: CLASSIFIER_BOX_TOOL,
85
+ description: CLASSIFIER_BOX_TOOL_DESCRIPTION,
86
+ inputSchema: boxParameters,
87
+ annotations: localAnnotations,
88
+ },
89
+ ];
90
+
91
+ /** Return human-readable validation problems; an empty array means the arguments are valid. */
92
+ export function validateMcpToolArguments(tool: ClassifierMcpToolDefinition, args: unknown): string[] {
93
+ if (Value.Check(tool.inputSchema, args)) return [];
94
+ const problems = new Set<string>();
95
+ for (const error of Value.Errors(tool.inputSchema, args)) {
96
+ if (error.keyword === 'boolean') continue;
97
+ const path = error.instancePath || 'arguments';
98
+ const unknown = error.keyword === 'additionalProperties'
99
+ ? (error.params as { additionalProperties?: string[] }).additionalProperties
100
+ : undefined;
101
+ problems.add(unknown?.length ? `${path}: unknown properties ${unknown.join(', ')}` : `${path}: ${error.message}`);
102
+ }
103
+ return problems.size > 0 ? [...problems] : ['arguments do not match the input schema'];
104
+ }