@harnesys/sdk 1.0.0 → 1.1.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.
package/README.md CHANGED
@@ -8,7 +8,7 @@ Leaf package for addon authors. Implements the addon platform spec (`docs/ADDONS
8
8
  bun add @harnesys/sdk
9
9
  ```
10
10
 
11
- Version `1.0.0` tracks the addon platform contract (`platform: 1`). The SDK ships TypeScript sources for Bun and compiled ESM plus declarations in `dist/`; see [Распространение SDK](../../docs/add-ons/sdk.md#распространение-sdk) for the export modes and the consumer `tsconfig` shape.
11
+ Version `1.0.0` tracks the addon platform contract (`platform: 1`); `1.1.0` adds tool schema validation to the fake host. The SDK ships TypeScript sources for Bun and compiled ESM plus declarations in `dist/`; see [Распространение SDK](../../docs/add-ons/sdk.md#распространение-sdk) for the export modes and the consumer `tsconfig` shape.
12
12
 
13
13
  ## Layout
14
14
 
@@ -0,0 +1,12 @@
1
+ export interface SchemaValueIssue {
2
+ path: string;
3
+ message: string;
4
+ }
5
+ /**
6
+ * Validates a value against the §6.5 JSON Schema subset (`type`, `properties`,
7
+ * `required`, `items`, `enum`, `const`, numeric and string bounds,
8
+ * `additionalProperties`, limited `oneOf`/`anyOf`, local `$defs`/`$ref`).
9
+ * Same contract the host applies to route request bodies; the fake host uses it
10
+ * to validate tool `inputSchema`/`outputSchema`.
11
+ */
12
+ export declare function schemaValueIssues(value: unknown, schema: Record<string, unknown>): SchemaValueIssue[];
@@ -0,0 +1,243 @@
1
+ const MAX_VALIDATION_DEPTH = 16;
2
+ /**
3
+ * Validates a value against the §6.5 JSON Schema subset (`type`, `properties`,
4
+ * `required`, `items`, `enum`, `const`, numeric and string bounds,
5
+ * `additionalProperties`, limited `oneOf`/`anyOf`, local `$defs`/`$ref`).
6
+ * Same contract the host applies to route request bodies; the fake host uses it
7
+ * to validate tool `inputSchema`/`outputSchema`.
8
+ */
9
+ export function schemaValueIssues(value, schema) {
10
+ const ctx = { root: schema, issues: [] };
11
+ validateNode(value, schema, '$', 0, ctx);
12
+ return ctx.issues;
13
+ }
14
+ function validateNode(value, node, path, depth, ctx) {
15
+ if (depth > MAX_VALIDATION_DEPTH) {
16
+ ctx.issues.push({ path, message: 'value nesting exceeds the maximum depth' });
17
+ return;
18
+ }
19
+ if (node.$ref !== undefined) {
20
+ validateRef(value, node.$ref, path, depth, ctx);
21
+ return;
22
+ }
23
+ if (!matchesUnion(value, node, path, ctx)) {
24
+ return;
25
+ }
26
+ if (!matchesEnum(value, node, path, ctx)) {
27
+ return;
28
+ }
29
+ if (node.const !== undefined && node.const !== value) {
30
+ ctx.issues.push({ path, message: 'value does not equal the const constraint' });
31
+ return;
32
+ }
33
+ if (typeof value === 'string') {
34
+ validateString(value, node, path, ctx);
35
+ }
36
+ else if (typeof value === 'number' && Number.isFinite(value)) {
37
+ validateNumber(value, node, path, ctx);
38
+ }
39
+ else if (Array.isArray(value)) {
40
+ validateArray(value, node, path, depth, ctx);
41
+ }
42
+ else if (isPlainObject(value)) {
43
+ validateObject(value, node, path, depth, ctx);
44
+ }
45
+ }
46
+ function validateRef(value, ref, path, depth, ctx) {
47
+ const resolved = resolveRef(ctx.root, ref);
48
+ if (resolved === null) {
49
+ ctx.issues.push({ path, message: `unresolvable $ref '${ref}'` });
50
+ return;
51
+ }
52
+ validateNode(value, resolved, path, depth + 1, ctx);
53
+ }
54
+ function matchesUnion(value, node, path, ctx) {
55
+ if (node.oneOf !== undefined && node.oneOf.length > 0) {
56
+ const matches = node.oneOf.filter((branch) => branchIssues(value, branch, ctx) === 0).length;
57
+ if (matches !== 1) {
58
+ ctx.issues.push({ path, message: `expected exactly one oneOf branch, matched ${matches}` });
59
+ return false;
60
+ }
61
+ return true;
62
+ }
63
+ if (node.anyOf !== undefined && node.anyOf.length > 0) {
64
+ if (!node.anyOf.some((branch) => branchIssues(value, branch, ctx) === 0)) {
65
+ ctx.issues.push({ path, message: 'value matches no anyOf branch' });
66
+ return false;
67
+ }
68
+ return true;
69
+ }
70
+ if (!matchesType(value, node.type)) {
71
+ ctx.issues.push({ path, message: `expected ${node.type ?? 'any'}, got ${kindOf(value)}` });
72
+ return false;
73
+ }
74
+ return true;
75
+ }
76
+ function matchesEnum(value, node, path, ctx) {
77
+ if (node.enum === undefined || node.enum.some((entry) => entry === value)) {
78
+ return true;
79
+ }
80
+ ctx.issues.push({ path, message: 'value is not one of the allowed enum entries' });
81
+ return false;
82
+ }
83
+ function matchesType(value, expected) {
84
+ if (expected === undefined) {
85
+ return true;
86
+ }
87
+ switch (expected) {
88
+ case 'string':
89
+ return typeof value === 'string';
90
+ case 'boolean':
91
+ return typeof value === 'boolean';
92
+ case 'null':
93
+ return value === null;
94
+ case 'integer':
95
+ return typeof value === 'number' && Number.isInteger(value);
96
+ case 'number':
97
+ return typeof value === 'number' && Number.isFinite(value);
98
+ case 'array':
99
+ return Array.isArray(value);
100
+ case 'object':
101
+ return isPlainObject(value);
102
+ default:
103
+ return true;
104
+ }
105
+ }
106
+ function validateString(value, node, path, ctx) {
107
+ if (node.minLength !== undefined && value.length < node.minLength) {
108
+ ctx.issues.push({ path, message: `length is below minLength ${node.minLength}` });
109
+ }
110
+ if (node.maxLength !== undefined && value.length > node.maxLength) {
111
+ ctx.issues.push({ path, message: `length exceeds maxLength ${node.maxLength}` });
112
+ }
113
+ if (node.pattern === undefined) {
114
+ return;
115
+ }
116
+ try {
117
+ if (!new RegExp(node.pattern).test(value)) {
118
+ ctx.issues.push({ path, message: `value does not match pattern '${node.pattern}'` });
119
+ }
120
+ }
121
+ catch {
122
+ ctx.issues.push({ path, message: `schema pattern '${node.pattern}' is not a valid regex` });
123
+ }
124
+ }
125
+ function validateNumber(value, node, path, ctx) {
126
+ if (node.minimum !== undefined && value < node.minimum) {
127
+ ctx.issues.push({ path, message: `value is below minimum ${node.minimum}` });
128
+ }
129
+ if (node.maximum !== undefined && value > node.maximum) {
130
+ ctx.issues.push({ path, message: `value exceeds maximum ${node.maximum}` });
131
+ }
132
+ if (node.exclusiveMinimum !== undefined && value <= node.exclusiveMinimum) {
133
+ ctx.issues.push({
134
+ path,
135
+ message: `value is not above exclusiveMinimum ${node.exclusiveMinimum}`,
136
+ });
137
+ }
138
+ if (node.exclusiveMaximum !== undefined && value >= node.exclusiveMaximum) {
139
+ ctx.issues.push({
140
+ path,
141
+ message: `value is not below exclusiveMaximum ${node.exclusiveMaximum}`,
142
+ });
143
+ }
144
+ }
145
+ function validateArray(value, node, path, depth, ctx) {
146
+ if (node.minItems !== undefined && value.length < node.minItems) {
147
+ ctx.issues.push({ path, message: `array has fewer than minItems ${node.minItems}` });
148
+ }
149
+ if (node.maxItems !== undefined && value.length > node.maxItems) {
150
+ ctx.issues.push({ path, message: `array has more than maxItems ${node.maxItems}` });
151
+ }
152
+ if (node.uniqueItems === true && hasDuplicates(value)) {
153
+ ctx.issues.push({ path, message: 'array entries are not unique' });
154
+ }
155
+ if (node.items === undefined) {
156
+ return;
157
+ }
158
+ const items = node.items;
159
+ if (Array.isArray(items)) {
160
+ for (const [index, item] of value.entries()) {
161
+ const itemSchema = items[index];
162
+ if (itemSchema !== undefined) {
163
+ validateNode(item, itemSchema, `${path}[${index}]`, depth + 1, ctx);
164
+ }
165
+ }
166
+ return;
167
+ }
168
+ for (const [index, item] of value.entries()) {
169
+ validateNode(item, items, `${path}[${index}]`, depth + 1, ctx);
170
+ }
171
+ }
172
+ function validateObject(value, node, path, depth, ctx) {
173
+ for (const key of node.required ?? []) {
174
+ if (!(key in value)) {
175
+ ctx.issues.push({ path, message: `missing required property '${key}'` });
176
+ }
177
+ }
178
+ const additional = node.additionalProperties;
179
+ if (additional === undefined || additional === true) {
180
+ validateDeclaredProperties(value, node, path, depth, ctx);
181
+ return;
182
+ }
183
+ for (const [key, child] of Object.entries(value)) {
184
+ const childPath = `${path}.${key}`;
185
+ const declared = node.properties?.[key];
186
+ if (declared !== undefined) {
187
+ validateNode(child, declared, childPath, depth + 1, ctx);
188
+ continue;
189
+ }
190
+ if (additional === false) {
191
+ ctx.issues.push({ path: childPath, message: 'property is not allowed by the schema' });
192
+ continue;
193
+ }
194
+ validateNode(child, additional, childPath, depth + 1, ctx);
195
+ }
196
+ }
197
+ function validateDeclaredProperties(value, node, path, depth, ctx) {
198
+ for (const [key, child] of Object.entries(node.properties ?? {})) {
199
+ if (key in value) {
200
+ validateNode(value[key], child, `${path}.${key}`, depth + 1, ctx);
201
+ }
202
+ }
203
+ }
204
+ function branchIssues(value, branch, ctx) {
205
+ const issues = [];
206
+ validateNode(value, branch, '$', 0, { root: ctx.root, issues });
207
+ return issues.length;
208
+ }
209
+ function resolveRef(root, ref) {
210
+ if (!ref.startsWith('#/')) {
211
+ return null;
212
+ }
213
+ let current = root;
214
+ for (const segment of ref.slice(2).split('/')) {
215
+ if (!isPlainObject(current)) {
216
+ return null;
217
+ }
218
+ current = current[segment];
219
+ }
220
+ return isPlainObject(current) ? current : null;
221
+ }
222
+ function hasDuplicates(value) {
223
+ const seen = new Set();
224
+ for (const entry of value) {
225
+ const key = JSON.stringify(entry);
226
+ if (seen.has(key)) {
227
+ return true;
228
+ }
229
+ }
230
+ return false;
231
+ }
232
+ function isPlainObject(value) {
233
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
234
+ }
235
+ function kindOf(value) {
236
+ if (value === null) {
237
+ return 'null';
238
+ }
239
+ if (Array.isArray(value)) {
240
+ return 'array';
241
+ }
242
+ return typeof value;
243
+ }
package/dist/index.d.ts CHANGED
@@ -6,6 +6,7 @@ export { defaultConfigValues, type FieldOption, FieldOptionSchema, type FieldOpt
6
6
  export { HOOK_SCHEMA_VERSION, type HookDescriptor, HookDescriptorSchema, HookOnSchema, hookFamily, } from './families/hook.ts';
7
7
  export { JOB_SCHEMA_VERSION, type JobDescriptor, JobDescriptorSchema, JobScheduleSchema, jobFamily, } from './families/job.ts';
8
8
  export { INPUT_SCHEMA_MAX_BYTES, INPUT_SCHEMA_MAX_DEPTH, type JsonSchemaSubset, JsonSchemaSubsetSchema, type SchemaViolation, validateInputSchema, } from './families/json-schema.ts';
9
+ export { type SchemaValueIssue, schemaValueIssues, } from './families/json-schema-value.ts';
9
10
  export { LSP_SCHEMA_VERSION, type LspDescriptor, LspDescriptorSchema, lspFamily, } from './families/lsp.ts';
10
11
  export { MCP_SCHEMA_VERSION, type McpDescriptor, McpDescriptorSchema, mcpFamily, } from './families/mcp.ts';
11
12
  export { FAMILY_NAMES, type FamilyDefinition, familyDefinition, familyRegistry, } from './families/registry.ts';
package/dist/index.js CHANGED
@@ -6,6 +6,7 @@ export { defaultConfigValues, FieldOptionSchema, FieldOptionsFromSchema, FieldSp
6
6
  export { HOOK_SCHEMA_VERSION, HookDescriptorSchema, HookOnSchema, hookFamily, } from "./families/hook.js";
7
7
  export { JOB_SCHEMA_VERSION, JobDescriptorSchema, JobScheduleSchema, jobFamily, } from "./families/job.js";
8
8
  export { INPUT_SCHEMA_MAX_BYTES, INPUT_SCHEMA_MAX_DEPTH, JsonSchemaSubsetSchema, validateInputSchema, } from "./families/json-schema.js";
9
+ export { schemaValueIssues, } from "./families/json-schema-value.js";
9
10
  export { LSP_SCHEMA_VERSION, LspDescriptorSchema, lspFamily, } from "./families/lsp.js";
10
11
  export { MCP_SCHEMA_VERSION, McpDescriptorSchema, mcpFamily, } from "./families/mcp.js";
11
12
  export { FAMILY_NAMES, familyDefinition, familyRegistry, } from "./families/registry.js";
@@ -1,3 +1,4 @@
1
+ import { schemaValueIssues } from "../families/json-schema-value.js";
1
2
  import { AddonError } from "../protocol/error.js";
2
3
  import { methodSpec } from "../protocol/map.js";
3
4
  import { createAddonRuntime } from "../runtime.js";
@@ -126,8 +127,47 @@ export function createFakeHost(options) {
126
127
  };
127
128
  const controller = new AbortController();
128
129
  const withMeta = method === 'initialize' ? params : { ...params, _meta: meta };
130
+ if (method === 'tools.call') {
131
+ return deliverToolCall(withMeta, controller.signal);
132
+ }
129
133
  return runtime.handleRequest(method, withMeta, controller.signal);
130
134
  }
135
+ // Mirrors the real host: tool input is validated against the descriptor's
136
+ // `inputSchema` before the call and the output against `outputSchema` after
137
+ // it (see docs/external-addons/contributions.md, tool-pack).
138
+ async function deliverToolCall(params, signal) {
139
+ const tool = typeof params.tool === 'string' ? params.tool : '';
140
+ const descriptor = toolDescriptor(tool);
141
+ const input = isPlainObject(params.input) ? params.input : {};
142
+ const inputIssues = descriptor?.inputSchema
143
+ ? schemaValueIssues(input, descriptor.inputSchema)
144
+ : [];
145
+ if (inputIssues.length > 0) {
146
+ throw new AddonError('invalid_params', {
147
+ detail: `tools.call ${tool}: ${describeIssue(inputIssues)}`,
148
+ });
149
+ }
150
+ const result = (await runtime.handleRequest('tools.call', params, signal));
151
+ const outputIssues = descriptor?.outputSchema
152
+ ? schemaValueIssues(result.output ?? {}, descriptor.outputSchema)
153
+ : [];
154
+ if (outputIssues.length > 0) {
155
+ throw new AddonError('invalid_response', {
156
+ detail: `tools.call ${tool}: ${describeIssue(outputIssues)}`,
157
+ });
158
+ }
159
+ return result;
160
+ }
161
+ function toolDescriptor(tool) {
162
+ return toolSchemaDescriptor(manifest, tool);
163
+ }
164
+ function describeIssue(issues) {
165
+ const issue = issues[0];
166
+ if (!issue) {
167
+ return 'validation failed';
168
+ }
169
+ return `${issue.path === '$' ? 'params' : issue.path}: ${issue.message}`;
170
+ }
131
171
  async function dispatchAddonToHost(method, rawParams) {
132
172
  const spec = methodSpec(method);
133
173
  if (spec?.direction !== 'addon-to-host') {
@@ -150,3 +190,28 @@ export function createFakeHost(options) {
150
190
  }
151
191
  return host;
152
192
  }
193
+ function isPlainObject(value) {
194
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
195
+ }
196
+ function toolSchemaDescriptor(manifest, tool) {
197
+ for (const contribution of manifest.contributions) {
198
+ if (contribution.family !== 'tool-pack') {
199
+ continue;
200
+ }
201
+ const entry = toolEntry(contribution.descriptor, tool);
202
+ if (entry) {
203
+ return {
204
+ ...(isPlainObject(entry.inputSchema) ? { inputSchema: entry.inputSchema } : {}),
205
+ ...(isPlainObject(entry.outputSchema) ? { outputSchema: entry.outputSchema } : {}),
206
+ };
207
+ }
208
+ }
209
+ return null;
210
+ }
211
+ function toolEntry(descriptor, tool) {
212
+ const tools = descriptor.tools;
213
+ if (!Array.isArray(tools)) {
214
+ return null;
215
+ }
216
+ return (tools.find((candidate) => isPlainObject(candidate) && candidate.name === tool) ?? null);
217
+ }
@@ -1,4 +1,5 @@
1
1
  import type { ResolvedAddonDefinition } from '../define-addon.ts';
2
2
  import type { AddonManifest } from '../manifest/manifest.ts';
3
3
  export declare function validManifest(): AddonManifest;
4
+ export declare function toolPackManifest(tools: Array<Record<string, unknown>>): AddonManifest;
4
5
  export declare function demoDefinition(): ResolvedAddonDefinition;
@@ -46,6 +46,23 @@ export function validManifest() {
46
46
  ],
47
47
  };
48
48
  }
49
+ export function toolPackManifest(tools) {
50
+ return {
51
+ ...validManifest(),
52
+ contributions: [
53
+ {
54
+ id: 'pack',
55
+ family: 'tool-pack',
56
+ descriptor: {
57
+ name: 'example',
58
+ title: 'Example tools',
59
+ description: 'Tools for the demo',
60
+ tools,
61
+ },
62
+ },
63
+ ],
64
+ };
65
+ }
49
66
  export function demoDefinition() {
50
67
  return defineAddon({
51
68
  tools: {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@harnesys/sdk",
3
- "version": "1.0.0",
3
+ "version": "1.1.0",
4
4
  "description": "Add-on SDK for Harnesys: manifest, contributions, JSON-RPC protocol, permissions, defineAddon, host client and a testing fake host.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -0,0 +1,322 @@
1
+ import type { JsonSchemaSubset } from './json-schema.ts';
2
+
3
+ export interface SchemaValueIssue {
4
+ path: string;
5
+ message: string;
6
+ }
7
+
8
+ interface ValidationContext {
9
+ root: Record<string, unknown>;
10
+ issues: SchemaValueIssue[];
11
+ }
12
+
13
+ const MAX_VALIDATION_DEPTH = 16;
14
+
15
+ /**
16
+ * Validates a value against the §6.5 JSON Schema subset (`type`, `properties`,
17
+ * `required`, `items`, `enum`, `const`, numeric and string bounds,
18
+ * `additionalProperties`, limited `oneOf`/`anyOf`, local `$defs`/`$ref`).
19
+ * Same contract the host applies to route request bodies; the fake host uses it
20
+ * to validate tool `inputSchema`/`outputSchema`.
21
+ */
22
+ export function schemaValueIssues(
23
+ value: unknown,
24
+ schema: Record<string, unknown>,
25
+ ): SchemaValueIssue[] {
26
+ const ctx: ValidationContext = { root: schema, issues: [] };
27
+ validateNode(value, schema as JsonSchemaSubset, '$', 0, ctx);
28
+ return ctx.issues;
29
+ }
30
+
31
+ function validateNode(
32
+ value: unknown,
33
+ node: JsonSchemaSubset,
34
+ path: string,
35
+ depth: number,
36
+ ctx: ValidationContext,
37
+ ): void {
38
+ if (depth > MAX_VALIDATION_DEPTH) {
39
+ ctx.issues.push({ path, message: 'value nesting exceeds the maximum depth' });
40
+ return;
41
+ }
42
+ if (node.$ref !== undefined) {
43
+ validateRef(value, node.$ref, path, depth, ctx);
44
+ return;
45
+ }
46
+ if (!matchesUnion(value, node, path, ctx)) {
47
+ return;
48
+ }
49
+ if (!matchesEnum(value, node, path, ctx)) {
50
+ return;
51
+ }
52
+ if (node.const !== undefined && node.const !== value) {
53
+ ctx.issues.push({ path, message: 'value does not equal the const constraint' });
54
+ return;
55
+ }
56
+ if (typeof value === 'string') {
57
+ validateString(value, node, path, ctx);
58
+ } else if (typeof value === 'number' && Number.isFinite(value)) {
59
+ validateNumber(value, node, path, ctx);
60
+ } else if (Array.isArray(value)) {
61
+ validateArray(value, node, path, depth, ctx);
62
+ } else if (isPlainObject(value)) {
63
+ validateObject(value, node, path, depth, ctx);
64
+ }
65
+ }
66
+
67
+ function validateRef(
68
+ value: unknown,
69
+ ref: string,
70
+ path: string,
71
+ depth: number,
72
+ ctx: ValidationContext,
73
+ ): void {
74
+ const resolved = resolveRef(ctx.root, ref);
75
+ if (resolved === null) {
76
+ ctx.issues.push({ path, message: `unresolvable $ref '${ref}'` });
77
+ return;
78
+ }
79
+ validateNode(value, resolved, path, depth + 1, ctx);
80
+ }
81
+
82
+ function matchesUnion(
83
+ value: unknown,
84
+ node: JsonSchemaSubset,
85
+ path: string,
86
+ ctx: ValidationContext,
87
+ ): boolean {
88
+ if (node.oneOf !== undefined && node.oneOf.length > 0) {
89
+ const matches = node.oneOf.filter((branch) => branchIssues(value, branch, ctx) === 0).length;
90
+ if (matches !== 1) {
91
+ ctx.issues.push({ path, message: `expected exactly one oneOf branch, matched ${matches}` });
92
+ return false;
93
+ }
94
+ return true;
95
+ }
96
+ if (node.anyOf !== undefined && node.anyOf.length > 0) {
97
+ if (!node.anyOf.some((branch) => branchIssues(value, branch, ctx) === 0)) {
98
+ ctx.issues.push({ path, message: 'value matches no anyOf branch' });
99
+ return false;
100
+ }
101
+ return true;
102
+ }
103
+ if (!matchesType(value, node.type)) {
104
+ ctx.issues.push({ path, message: `expected ${node.type ?? 'any'}, got ${kindOf(value)}` });
105
+ return false;
106
+ }
107
+ return true;
108
+ }
109
+
110
+ function matchesEnum(
111
+ value: unknown,
112
+ node: JsonSchemaSubset,
113
+ path: string,
114
+ ctx: ValidationContext,
115
+ ): boolean {
116
+ if (node.enum === undefined || node.enum.some((entry) => entry === value)) {
117
+ return true;
118
+ }
119
+ ctx.issues.push({ path, message: 'value is not one of the allowed enum entries' });
120
+ return false;
121
+ }
122
+
123
+ type SchemaType = 'object' | 'array' | 'string' | 'number' | 'integer' | 'boolean' | 'null';
124
+
125
+ function matchesType(value: unknown, expected: SchemaType | undefined): boolean {
126
+ if (expected === undefined) {
127
+ return true;
128
+ }
129
+ switch (expected) {
130
+ case 'string':
131
+ return typeof value === 'string';
132
+ case 'boolean':
133
+ return typeof value === 'boolean';
134
+ case 'null':
135
+ return value === null;
136
+ case 'integer':
137
+ return typeof value === 'number' && Number.isInteger(value);
138
+ case 'number':
139
+ return typeof value === 'number' && Number.isFinite(value);
140
+ case 'array':
141
+ return Array.isArray(value);
142
+ case 'object':
143
+ return isPlainObject(value);
144
+ default:
145
+ return true;
146
+ }
147
+ }
148
+
149
+ function validateString(
150
+ value: string,
151
+ node: JsonSchemaSubset,
152
+ path: string,
153
+ ctx: ValidationContext,
154
+ ): void {
155
+ if (node.minLength !== undefined && value.length < node.minLength) {
156
+ ctx.issues.push({ path, message: `length is below minLength ${node.minLength}` });
157
+ }
158
+ if (node.maxLength !== undefined && value.length > node.maxLength) {
159
+ ctx.issues.push({ path, message: `length exceeds maxLength ${node.maxLength}` });
160
+ }
161
+ if (node.pattern === undefined) {
162
+ return;
163
+ }
164
+ try {
165
+ if (!new RegExp(node.pattern).test(value)) {
166
+ ctx.issues.push({ path, message: `value does not match pattern '${node.pattern}'` });
167
+ }
168
+ } catch {
169
+ ctx.issues.push({ path, message: `schema pattern '${node.pattern}' is not a valid regex` });
170
+ }
171
+ }
172
+
173
+ function validateNumber(
174
+ value: number,
175
+ node: JsonSchemaSubset,
176
+ path: string,
177
+ ctx: ValidationContext,
178
+ ): void {
179
+ if (node.minimum !== undefined && value < node.minimum) {
180
+ ctx.issues.push({ path, message: `value is below minimum ${node.minimum}` });
181
+ }
182
+ if (node.maximum !== undefined && value > node.maximum) {
183
+ ctx.issues.push({ path, message: `value exceeds maximum ${node.maximum}` });
184
+ }
185
+ if (node.exclusiveMinimum !== undefined && value <= node.exclusiveMinimum) {
186
+ ctx.issues.push({
187
+ path,
188
+ message: `value is not above exclusiveMinimum ${node.exclusiveMinimum}`,
189
+ });
190
+ }
191
+ if (node.exclusiveMaximum !== undefined && value >= node.exclusiveMaximum) {
192
+ ctx.issues.push({
193
+ path,
194
+ message: `value is not below exclusiveMaximum ${node.exclusiveMaximum}`,
195
+ });
196
+ }
197
+ }
198
+
199
+ function validateArray(
200
+ value: unknown[],
201
+ node: JsonSchemaSubset,
202
+ path: string,
203
+ depth: number,
204
+ ctx: ValidationContext,
205
+ ): void {
206
+ if (node.minItems !== undefined && value.length < node.minItems) {
207
+ ctx.issues.push({ path, message: `array has fewer than minItems ${node.minItems}` });
208
+ }
209
+ if (node.maxItems !== undefined && value.length > node.maxItems) {
210
+ ctx.issues.push({ path, message: `array has more than maxItems ${node.maxItems}` });
211
+ }
212
+ if (node.uniqueItems === true && hasDuplicates(value)) {
213
+ ctx.issues.push({ path, message: 'array entries are not unique' });
214
+ }
215
+ if (node.items === undefined) {
216
+ return;
217
+ }
218
+ const items = node.items;
219
+ if (Array.isArray(items)) {
220
+ for (const [index, item] of value.entries()) {
221
+ const itemSchema = items[index];
222
+ if (itemSchema !== undefined) {
223
+ validateNode(item, itemSchema, `${path}[${index}]`, depth + 1, ctx);
224
+ }
225
+ }
226
+ return;
227
+ }
228
+ for (const [index, item] of value.entries()) {
229
+ validateNode(item, items, `${path}[${index}]`, depth + 1, ctx);
230
+ }
231
+ }
232
+
233
+ function validateObject(
234
+ value: Record<string, unknown>,
235
+ node: JsonSchemaSubset,
236
+ path: string,
237
+ depth: number,
238
+ ctx: ValidationContext,
239
+ ): void {
240
+ for (const key of node.required ?? []) {
241
+ if (!(key in value)) {
242
+ ctx.issues.push({ path, message: `missing required property '${key}'` });
243
+ }
244
+ }
245
+ const additional = node.additionalProperties;
246
+ if (additional === undefined || additional === true) {
247
+ validateDeclaredProperties(value, node, path, depth, ctx);
248
+ return;
249
+ }
250
+ for (const [key, child] of Object.entries(value)) {
251
+ const childPath = `${path}.${key}`;
252
+ const declared = node.properties?.[key];
253
+ if (declared !== undefined) {
254
+ validateNode(child, declared, childPath, depth + 1, ctx);
255
+ continue;
256
+ }
257
+ if (additional === false) {
258
+ ctx.issues.push({ path: childPath, message: 'property is not allowed by the schema' });
259
+ continue;
260
+ }
261
+ validateNode(child, additional, childPath, depth + 1, ctx);
262
+ }
263
+ }
264
+
265
+ function validateDeclaredProperties(
266
+ value: Record<string, unknown>,
267
+ node: JsonSchemaSubset,
268
+ path: string,
269
+ depth: number,
270
+ ctx: ValidationContext,
271
+ ): void {
272
+ for (const [key, child] of Object.entries(node.properties ?? {})) {
273
+ if (key in value) {
274
+ validateNode(value[key], child, `${path}.${key}`, depth + 1, ctx);
275
+ }
276
+ }
277
+ }
278
+
279
+ function branchIssues(value: unknown, branch: JsonSchemaSubset, ctx: ValidationContext): number {
280
+ const issues: SchemaValueIssue[] = [];
281
+ validateNode(value, branch, '$', 0, { root: ctx.root, issues });
282
+ return issues.length;
283
+ }
284
+
285
+ function resolveRef(root: Record<string, unknown>, ref: string): JsonSchemaSubset | null {
286
+ if (!ref.startsWith('#/')) {
287
+ return null;
288
+ }
289
+ let current: unknown = root;
290
+ for (const segment of ref.slice(2).split('/')) {
291
+ if (!isPlainObject(current)) {
292
+ return null;
293
+ }
294
+ current = current[segment];
295
+ }
296
+ return isPlainObject(current) ? (current as JsonSchemaSubset) : null;
297
+ }
298
+
299
+ function hasDuplicates(value: unknown[]): boolean {
300
+ const seen = new Set<string>();
301
+ for (const entry of value) {
302
+ const key = JSON.stringify(entry);
303
+ if (seen.has(key)) {
304
+ return true;
305
+ }
306
+ }
307
+ return false;
308
+ }
309
+
310
+ function isPlainObject(value: unknown): value is Record<string, unknown> {
311
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
312
+ }
313
+
314
+ function kindOf(value: unknown): string {
315
+ if (value === null) {
316
+ return 'null';
317
+ }
318
+ if (Array.isArray(value)) {
319
+ return 'array';
320
+ }
321
+ return typeof value;
322
+ }
package/src/index.ts CHANGED
@@ -95,6 +95,10 @@ export {
95
95
  type SchemaViolation,
96
96
  validateInputSchema,
97
97
  } from './families/json-schema.ts';
98
+ export {
99
+ type SchemaValueIssue,
100
+ schemaValueIssues,
101
+ } from './families/json-schema-value.ts';
98
102
  export {
99
103
  LSP_SCHEMA_VERSION,
100
104
  type LspDescriptor,
@@ -1,4 +1,5 @@
1
1
  import type { ResolvedAddonDefinition } from '../define-addon.ts';
2
+ import { type SchemaValueIssue, schemaValueIssues } from '../families/json-schema-value.ts';
2
3
  import type { HostChannel } from '../host-client.ts';
3
4
  import type { AddonManifest } from '../manifest/manifest.ts';
4
5
  import { AddonError } from '../protocol/error.ts';
@@ -232,9 +233,56 @@ export function createFakeHost(options: FakeHostOptions): FakeHost {
232
233
  const controller = new AbortController();
233
234
  const withMeta =
234
235
  method === 'initialize' ? params : { ...(params as Record<string, unknown>), _meta: meta };
236
+ if (method === 'tools.call') {
237
+ return deliverToolCall(withMeta as Record<string, unknown>, controller.signal);
238
+ }
235
239
  return runtime.handleRequest(method, withMeta, controller.signal);
236
240
  }
237
241
 
242
+ // Mirrors the real host: tool input is validated against the descriptor's
243
+ // `inputSchema` before the call and the output against `outputSchema` after
244
+ // it (see docs/external-addons/contributions.md, tool-pack).
245
+ async function deliverToolCall(
246
+ params: Record<string, unknown>,
247
+ signal: AbortSignal,
248
+ ): Promise<unknown> {
249
+ const tool = typeof params.tool === 'string' ? params.tool : '';
250
+ const descriptor = toolDescriptor(tool);
251
+ const input = isPlainObject(params.input) ? params.input : {};
252
+ const inputIssues = descriptor?.inputSchema
253
+ ? schemaValueIssues(input, descriptor.inputSchema)
254
+ : [];
255
+ if (inputIssues.length > 0) {
256
+ throw new AddonError('invalid_params', {
257
+ detail: `tools.call ${tool}: ${describeIssue(inputIssues)}`,
258
+ });
259
+ }
260
+ const result = (await runtime.handleRequest('tools.call', params, signal)) as {
261
+ output: unknown;
262
+ };
263
+ const outputIssues = descriptor?.outputSchema
264
+ ? schemaValueIssues(result.output ?? {}, descriptor.outputSchema)
265
+ : [];
266
+ if (outputIssues.length > 0) {
267
+ throw new AddonError('invalid_response', {
268
+ detail: `tools.call ${tool}: ${describeIssue(outputIssues)}`,
269
+ });
270
+ }
271
+ return result;
272
+ }
273
+
274
+ function toolDescriptor(tool: string): ToolSchemaDescriptor | null {
275
+ return toolSchemaDescriptor(manifest, tool);
276
+ }
277
+
278
+ function describeIssue(issues: SchemaValueIssue[]): string {
279
+ const issue = issues[0];
280
+ if (!issue) {
281
+ return 'validation failed';
282
+ }
283
+ return `${issue.path === '$' ? 'params' : issue.path}: ${issue.message}`;
284
+ }
285
+
238
286
  async function dispatchAddonToHost(method: string, rawParams: unknown): Promise<unknown> {
239
287
  const spec = methodSpec(method);
240
288
  if (spec?.direction !== 'addon-to-host') {
@@ -259,3 +307,44 @@ export function createFakeHost(options: FakeHostOptions): FakeHost {
259
307
 
260
308
  return host;
261
309
  }
310
+
311
+ function isPlainObject(value: unknown): value is Record<string, unknown> {
312
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
313
+ }
314
+
315
+ interface ToolSchemaDescriptor {
316
+ inputSchema?: Record<string, unknown>;
317
+ outputSchema?: Record<string, unknown>;
318
+ }
319
+
320
+ function toolSchemaDescriptor(manifest: AddonManifest, tool: string): ToolSchemaDescriptor | null {
321
+ for (const contribution of manifest.contributions) {
322
+ if (contribution.family !== 'tool-pack') {
323
+ continue;
324
+ }
325
+ const entry = toolEntry(contribution.descriptor, tool);
326
+ if (entry) {
327
+ return {
328
+ ...(isPlainObject(entry.inputSchema) ? { inputSchema: entry.inputSchema } : {}),
329
+ ...(isPlainObject(entry.outputSchema) ? { outputSchema: entry.outputSchema } : {}),
330
+ };
331
+ }
332
+ }
333
+ return null;
334
+ }
335
+
336
+ function toolEntry(
337
+ descriptor: Record<string, unknown>,
338
+ tool: string,
339
+ ): Record<string, unknown> | null {
340
+ const tools = descriptor.tools;
341
+ if (!Array.isArray(tools)) {
342
+ return null;
343
+ }
344
+ return (
345
+ tools.find(
346
+ (candidate): candidate is Record<string, unknown> =>
347
+ isPlainObject(candidate) && candidate.name === tool,
348
+ ) ?? null
349
+ );
350
+ }
@@ -50,6 +50,24 @@ export function validManifest(): AddonManifest {
50
50
  };
51
51
  }
52
52
 
53
+ export function toolPackManifest(tools: Array<Record<string, unknown>>): AddonManifest {
54
+ return {
55
+ ...validManifest(),
56
+ contributions: [
57
+ {
58
+ id: 'pack',
59
+ family: 'tool-pack',
60
+ descriptor: {
61
+ name: 'example',
62
+ title: 'Example tools',
63
+ description: 'Tools for the demo',
64
+ tools,
65
+ },
66
+ },
67
+ ],
68
+ };
69
+ }
70
+
53
71
  export function demoDefinition(): ResolvedAddonDefinition {
54
72
  return defineAddon({
55
73
  tools: {