MCP Tool Development and Anti-Drift Maintenance
MCP tools are the primary interface between agents and the Myco intelligence pipeline. Each tool requires a coordinated schema ↔ handler ↔ documentation triad that can drift over time, causing silent agent failures. This skill covers the complete development lifecycle and maintenance procedures to prevent drift regressions.
Prerequisites
- Working Myco development environment with
packages/myco/src/tools/ structure
- Understanding of JSON Schema for parameter definitions
- Familiarity with TypeScript handler patterns and DaemonClient usage
- Knowledge of local vs cloud MCP bifurcation model
- Understanding of shared tool-runtime supporting multiple transports (MCP stdio, HTTP MCP, CLI)
Procedure A: Schema Definition
Define the tool interface in packages/myco/src/tools/definitions.ts (shared tool-runtime definitions):
Add tool name constant at the top of the file:
export const TOOL_MY_NEW_TOOL = 'myco_my_new_tool';
Add schema entry to the appropriate array (TOOL_DEFINITIONS for local tools, COLLECTIVE_TOOL_DEFINITIONS for Collective-dependent tools):
{
name: TOOL_MY_NEW_TOOL,
description: 'Brief description of what this tool does — agents use this for selection decisions',
cortex: {
guidance: 'Clear guidance for when to use this tool vs alternatives',
priority: 50, // Default 100, lower numbers = higher priority
requiresTeam: false, // Set true if requires team sync
requiresCollective: false, // Set true if requires Collective connection
},
annotations: {
readOnlyHint: true, // False if tool mutates state
destructiveHint: false, // True if tool can destroy data
idempotentHint: true, // False if repeated calls cause different effects
openWorldHint: false, // True if tool reaches outside local vault
},
inputSchema: {
type: 'object' as const,
properties: {
param_name: {
type: 'string',
description: 'Clear description for agents — include format examples'
},
optional_param: {
type: 'number',
description: 'Optional parameter with default behavior explained'
}
},
required: ['param_name']
}
}
Use descriptive parameter names — agents rely on semantic meaning. session_id is better than id, batch_limit is better than limit.
Document every parameter thoroughly — the description is what agents use to understand usage. Include examples for complex formats.
Set annotations correctly — readOnlyHint: true for read-only tools, destructiveHint: true for tools that can destroy data.
Configure cortex metadata — set requiresCollective: true for tools that only work when connected to a Collective.
Avoid OpenAI strict mode incompatibilities — OpenAI's strict JSON Schema mode rejects oneOf, anyOf, allOf, enum, and not keywords at the top level. Use simple types with clear descriptions instead:
// BAD: OpenAI strict mode rejects this
{
param_status: {
enum: ['active', 'inactive', 'pending'],
description: 'Status value'
}
}
// GOOD: Use string with enum values in description
{
param_status: {
type: 'string',
description: 'Status value. Must be one of: active, inactive, pending'
}
}
Avoid Zod refinement-like patterns — Schema constructs that imply Zod refinements cause silent tool registration failures across runtimes. Never use .default(), .min(), .max(), or .refine() patterns in schema definitions:
// BAD: Implies Zod refinements that cause registration failures
{
limit: {
type: 'number',
default: 10, // Zod .default() - causes registration failure
minimum: 1, // Zod .min() - causes registration failure
maximum: 100 // Zod .max() - causes registration failure
}
}
// GOOD: Use plain schema with behavior described in documentation
{
limit: {
type: 'number',
description: 'Maximum items to return (1-100, defaults to 10 if omitted)'
}
}
Procedure B: Handler Implementation
Create the handler in packages/myco/src/tools/my-new-tool.ts:
Import required types and client:
import type { DaemonClient } from '@myco/hooks/client.js';
import { buildEndpoint } from './shared.js';
import { ToolFailure } from './error.js';
Define input and result types:
interface MyNewToolInput {
param_name: string;
optional_param?: number;
}
interface MyNewToolResult {
id: string;
status: string;
// ... other result fields
}
Implement the handler function with canonical error handling:
export async function handleMyNewTool(
input: MyNewToolInput,
client: DaemonClient,
): Promise<MyNewToolResult> {
// Validate all schema-declared parameters are consumed
const { param_name, optional_param = defaultValue } = input;
try {
const endpoint = buildEndpoint('/api/some-operation', {
param_name,
optional_param,
});
const response = await client.get(endpoint);
return response as MyNewToolResult;
} catch (error) {
// Use ToolFailure for consistent agent-facing error structure
throw new ToolFailure(`Failed to execute ${TOOL_MY_NEW_TOOL}`, {
cause: error,
context: { param_name, optional_param },
retriable: true, // Set false for permanent failures
});
}
}
Consume every schema parameter — handlers must accept exactly what the schema advertises. Renamed params, dropped fields, or undocumented required args cause agent call failures.
Use DaemonClient for vault access — all tools proxy through the daemon HTTP API via client.get(), client.post(), etc.
Handle errors with ToolFailure interface — import from packages/myco/src/tools/error.ts and wrap operational failures with structured context agents can understand:
import { ToolFailure } from './error.js';
// For parameter validation errors
throw new ToolFailure('Invalid parameter format', {
context: { param_name, expected: 'uuid format' },
retriable: false,
});
// For network/service failures
throw new ToolFailure('Daemon API unavailable', {
cause: originalError,
context: { endpoint, attempt: retryCount },
retriable: true,
});
Use canonical ToolFailure interface pattern — packages/myco/src/tools/error.ts exports the standardized ToolFailure class with structured error context. Always import and use this interface for agent-facing errors:
import { ToolFailure, ToolErrorCode } from './error.js';
// Standard validation failure
throw new ToolFailure('Parameter validation failed', {
code: ToolErrorCode.INVALID_INPUT,
context: { param: value, constraint: 'must be uuid' },
retriable: false,
});
// Service availability failure
throw new ToolFailure('Daemon service unavailable', {
code: ToolErrorCode.SERVICE_UNAVAILABLE,
cause: networkError,
context: { endpoint, timeout_ms: 5000 },
retriable: true,
});
Procedure C: Multi-Transport Registration
Register the tool once in the shared tool runtime. Stdio MCP, HTTP MCP, and the CLI all call through packages/myco/src/tools/index.ts; do not add transport-specific switch cases for normal tools.
Shared runtime registration in packages/myco/src/tools/index.ts:
[TOOL_MY_NEW_TOOL, async () => {
const { handleMyNewTool } = await import('./my-new-tool.js');
return {
handle: (input, client) => handleMyNewTool(input as MyNewToolInput, client),
summarize: (input, result) => ({ param_name: input.param_name }),
};
}],
MCP stdio and HTTP registration — packages/myco/src/mcp/server.ts exposes the shared definitions from packages/myco/src/tools/definitions.ts and dispatches calls through createMycoTools(...).
CLI registration — myco tool list and myco tool call use the same shared runtime, so the tool becomes available there after it is in TOOL_DEFINITIONS and HANDLERS.
Test multi-transport availability — verify tool appears in MCP client tool list, HTTP MCP endpoints, and CLI help for all configured transports.
Configure conditional enablement — Collective tools are automatically enabled/disabled based on collectiveEnabled flag across all transports. Local tools are always available.
Procedure D: Documentation Bundling and Regeneration
Each tool carries inline SKILL.md documentation bundled at compile time across all transports:
Write clear tool documentation covering:
- When to use this tool vs alternatives
- Parameter meanings and examples
- Expected response format
- Common usage patterns
- Transport-specific considerations (MCP stdio vs HTTP vs CLI)
Bundle at build time — documentation is compiled into handlers during build process and shared across transports.
Regenerate after schema changes:
npm run build # Rebuild bundled documentation for all transports
Verify agent-visible docs — test that agents receive current parameter names and descriptions across all transport types, not stale snapshots.
Never ship handler changes without doc updates — mismatched documentation causes agents to call tools with wrong parameters across any transport.
Procedure E: Anti-Drift Testing Patterns
Implement systematic checks to catch schema-handler-documentation drift across the shared tool-runtime:
Create test file template (example: packages/myco/src/tools/definitions.test.ts):
import { describe, test, expect } from 'vitest';
import { TOOL_DEFINITIONS, COLLECTIVE_TOOL_DEFINITIONS } from './definitions.js';
import * as handlers from './index.js';
Schema-handler parameter alignment test:
test('all schema parameters referenced in handler source', () => {
const allTools = [...TOOL_DEFINITIONS, ...COLLECTIVE_TOOL_DEFINITIONS];
for (const tool of allTools) {
const handlerName = getHandlerNameForTool(tool.name);
const handler = handlers[handlerName];
if (!handler) continue; // Skip stubs
const schemaParams = Object.keys(tool.inputSchema.properties || {});
const handlerSource = handler.toString();
schemaParams.forEach(param => {
expect(handlerSource).toContain(param);
});
}
});
Handler-schema synchronization test:
test('no orphaned handler parameters', () => {
// Parse handler destructuring patterns, compare to schema
// Fail if handler expects parameters not in schema
});
Tool name constant consistency:
test('all tool names match exported constants', () => {
const allTools = [...TOOL_DEFINITIONS, ...COLLECTIVE_TOOL_DEFINITIONS];
allTools.forEach(tool => {
expect(tool.name).toMatch(/^(myco_|collective_)/);
// Verify constant exists and matches
});
});
Multi-transport registration consistency:
test('all tools registered across transports', () => {
// Verify MCP stdio, HTTP MCP, and CLI registrations are consistent
// Check that transport-specific configurations align with shared definitions
});
Run after every handler or schema change — drift failures are silent until agents encounter them in production across any transport.
Procedure F: Stub vs Documented Tool Discipline
Handle incomplete or placeholder tools appropriately:
Mark stubs explicitly in schema description:
{
name: TOOL_MY_STUB,
description: '[STUB] This tool is registered but not yet implemented. Returns placeholder response only.',
// ... rest of definition
}
Implement stub handlers that return consistent "not implemented" responses:
export async function handleMyStub(): Promise<{ status: string }> {
return { status: 'not_implemented' };
}
Never document stubs as working tools — agents should know when functionality is incomplete across all transports.
Test stub behavior — ensure stubs return consistent responses rather than errors across MCP stdio, HTTP MCP, and CLI.
Remove or implement — stubs confuse agents across all transports. Either complete the implementation or remove from schema entirely.
Procedure G: Cloud vs Local Placement Decisions
Decide whether new tools belong in local or cloud MCP surface:
Default to local-only — new tools go in TOOL_DEFINITIONS unless they meet cloud criteria.
Promote to cloud surface only if tool is:
- Semantically read-only (no vault writes)
- Safe for federation (no sensitive data exposure)
- Required for cross-project Collective operations
Use COLLECTIVE_TOOL_DEFINITIONS for tools that require Collective connection state.
Test both surfaces — verify tools work correctly in local MCP and (if applicable) cloud federation.
Document placement rationale — explain why tool belongs in its chosen surface.
Procedure H: Skill Lifecycle Tool Registration Patterns
The skill lifecycle system requires specific tools that follow domain-specific registration patterns:
Register skill candidate management tools:
// In packages/myco/src/tools/definitions.ts
export const TOOL_SKILL_CANDIDATES = 'myco_skill_candidates';
{
name: TOOL_SKILL_CANDIDATES,
description: 'Manage skill candidates (identified topics that may become skills). Supports list, get, create, and update actions.',
cortex: {
guidance: 'Use for candidate discovery, approval workflows, and candidate lifecycle management',
priority: 80,
requiresTeam: false,
requiresCollective: false,
},
annotations: {
readOnlyHint: false,
destructiveHint: false,
idempotentHint: false,
openWorldHint: false,
},
inputSchema: {
type: 'object',
properties: {
action: {
type: 'string',
description: 'Action to perform: list, get, create, update, delete'
},
id: {
type: 'string',
description: 'Candidate ID (required for get/update)'
},
topic: {
type: 'string',
description: 'Skill topic (required for create)'
},
rationale: {
type: 'string',
description: 'Why this should be a skill (required for create)'
},
status: {
type: 'string',
description: 'Candidate status: identified, dismissed'
}
},
required: ['action']
}
}
Register skill record management tools:
export const TOOL_SKILL_RECORDS = 'myco_skill_records';
{
name: TOOL_SKILL_RECORDS,
description: 'Read, update, and delete skill records (materialized skills on disk). Supports list, get, update, and delete actions.',
cortex: {
guidance: 'Use for skill lifecycle operations — reading existing skills, updating status, managing skill evolution',
priority: 80,
},
inputSchema: {
type: 'object',
properties: {
action: { type: 'string', description: 'Action: list, get, update, delete' },
id: { type: 'string', description: 'Skill record ID or name (for get/update/delete)' },
status: { type: 'string', description: 'Filter by or new status: active, stale, retired' },
generation: { type: 'number', description: 'New generation number (for update)' }
},
required: ['action']
}
}
Register skill file writing tools:
export const TOOL_WRITE_SKILL = 'myco_write_skill';
{
name: TOOL_WRITE_SKILL,
description: 'Write a SKILL.md file to disk and create or update the corresponding skill record and lineage entry.',
cortex: {
guidance: 'Use when materializing a new skill from approved candidates or updating existing skills',
priority: 90,
},
annotations: {
readOnlyHint: false,
destructiveHint: false,
idempotentHint: false,
openWorldHint: false,
},
inputSchema: {
type: 'object',
properties: {
name: { type: 'string', description: 'Skill directory name (kebab-case, NO colon)' },
display_name: { type: 'string', description: 'Human-readable display name' },
description: { type: 'string', description: 'Short description of what the skill does' },
content: { type: 'string', description: 'Full SKILL.md content in markdown' },
rationale: { type: 'string', description: 'Why this skill was created or updated' },
candidate_id: { type: 'string', description: 'Candidate ID that prompted this skill creation' }
},
required: ['name', 'display_name', 'description', 'content']
}
}
Implement domain-specific validation patterns — skill tools require structural validation (YAML frontmatter, name prefixes, content length limits) that differs from general vault tools.
Test skill workflow integration — verify tools support the complete skill lifecycle: survey → approve → generate → evolve.
Procedure I: Shared Tool-Runtime Integration
Integrate with the shared tool-runtime supporting multiple transports:
Configure transport-specific behaviors:
// Different transports may need different error handling
const formatResponse = (result: any, transport: 'mcp' | 'http' | 'cli') => {
switch (transport) {
case 'mcp': return { content: [{ type: 'text', text: JSON.stringify(result, null, 2) }] };
case 'http': return result; // Direct JSON response
case 'cli': return formatCliOutput(result); // Human-readable format
}
};
Handle transport-specific authentication — MCP stdio uses connection-level auth, HTTP MCP uses token auth, CLI uses file-based auth.
Implement transport-aware logging:
logActivity(TOOL_NAME, {
...params,
transport: 'mcp|http|cli',
duration_ms: Date.now() - start
});
Test cross-transport consistency — verify same input produces equivalent results across MCP stdio, HTTP MCP, and CLI transports.
Document transport differences — note any transport-specific behaviors or limitations in tool documentation.
Procedure J: Grove Migration Context Handling
Handle project context changes with Grove migration architecture:
Update context injection patterns for Grove migration compatibility:
// Old: Direct project context injection
const context = await injectProjectContext(sessionId);
// New: Grove-aware context injection with fallback
const context = await injectGroveContext(sessionId, {
fallbackToLocal: true,
respectGroveConfig: true,
});
Handle Grove project boundaries when tools access cross-project resources:
export async function handleCrossProjectTool(
input: CrossProjectInput,
client: DaemonClient,
): Promise<CrossProjectResult> {
// Validate Grove project permissions before access
const groveAccess = await client.get('/api/grove/validate-access', {
targetProject: input.project_id,
operation: 'read',
});
if (!groveAccess.allowed) {
throw new ToolFailure('Grove access denied', {
context: { project_id: input.project_id, reason: groveAccess.reason },
retriable: false,
});
}
// Proceed with Grove-scoped operation
return await performGroveOperation(input, client);
}
Configure Grove-aware tool definitions with proper scope annotations:
{
name: TOOL_GROVE_AWARE,
description: 'Tool that operates across Grove project boundaries',
cortex: {
guidance: 'Use for cross-project operations in Grove environments',
requiresGrove: true, // New Grove requirement flag
},
annotations: {
crossProjectHint: true, // Indicates Grove boundary crossing
},
}
Test Grove project isolation — verify tools respect Grove project boundaries and fail gracefully when Grove is not configured.
Document Grove migration impact — note how tools behave differently in Grove vs traditional project structures.
Cross-Cutting Gotchas
Silent parameter drops: When schema defines a parameter but handler ignores it, agents receive no error — their input is silently dropped. This is the most common drift failure.
Documentation lag: Bundled SKILL.md becomes stale when handlers change. Always regenerate documentation after schema or handler modifications.
Cloud surface leakage: Write operations must never leak to cloud MCP surface. Default to local-only; promote to cloud only with explicit read-only verification.
Validation vs runtime divergence: Schema validation passes but handler expects different parameter structure. Test actual invocations, not just schema validation.
Collective conditional enablement: collective_* tools are enabled by Collective connection state. Test both connected and disconnected scenarios across all transports.
Tool name consistency: Use myco_ prefix for standard tools, collective_ prefix for Collective-dependent tools. Avoid generic names that conflict with other MCP servers.
Handler signature mismatch: All handlers must accept (input, client) parameters. Missing DaemonClient parameter causes registration failures.
Cross-runtime schema compatibility: OpenAI strict mode and Zod refinement patterns cause silent registration failures. Use plain JSON Schema types with descriptive documentation instead of complex validation constructs.
Skill tool registration gaps: Skill lifecycle operations require complete tool registration (candidates, records, write_skill) — missing any component breaks agent workflows. Always register skill tools as a complete set.
Shared tool-runtime path shifts: Tool definitions live in packages/myco/src/tools/definitions.ts. Update import paths and test references when the shared runtime moves.
Multi-transport registration complexity: Shared tool-runtime requires consistent registration across MCP stdio, HTTP MCP, and CLI transports. Test all transports when adding new tools.
Transport-specific error handling: Different transports expect different response formats. Implement transport-aware error formatting to prevent agent confusion.
ToolFailure anti-pattern: Never throw raw Error objects from handlers — always wrap with ToolFailure interface for consistent agent error handling. Missing structured error context causes agent confusion across all transports.
Code duplication across tool surface: Avoid copy-pasting handler patterns between tools. Extract shared utilities to packages/myco/src/tools/shared.ts and import consistently. Duplicated validation logic, error handling, and response formatting patterns create maintenance burden and drift risks across the unified tool surface. Use composition patterns instead:
// BAD: Duplicated validation across multiple tools
function handleToolA(input) {
if (!input.session_id || !isValidUuid(input.session_id)) {
throw new ToolFailure('Invalid session_id');
}
// ... tool logic
}
function handleToolB(input) {
if (!input.session_id || !isValidUuid(input.session_id)) {
throw new ToolFailure('Invalid session_id');
}
// ... tool logic (nearly identical validation)
}
// GOOD: Shared validation utilities
import { validateSessionId, validateRequiredString } from './shared.js';
function handleToolA(input) {
validateSessionId(input.session_id);
// ... tool logic
}
function handleToolB(input) {
validateSessionId(input.session_id);
// ... tool logic
}
Grove context injection failures: Tools accessing project context must handle Grove migration gracefully. Missing Grove-aware context injection causes failures in Grove environments while working in traditional project structures, creating environment-specific bugs.
1---
2name: myco-mcp-tool-development-lifecycle
3description: |
4 Comprehensive lifecycle for authoring, registering, documenting, and maintaining MCP tools in packages/myco/src/tools/ — covering schema definition in TOOL_DEFINITIONS arrays, handler implementation with DaemonClient patterns, shared tool-runtime registration, documentation bundling, anti-drift testing patterns, and cloud vs local placement decisions. Essential for maintaining the schema ↔ handler ↔ documentation triad that agents depend on for correct tool invocations, even when the user doesn't explicitly ask for MCP tool development.
5managed_by: myco
6user-invocable: true
7allowed-tools: Read, Edit, Write, Bash, Grep, Glob
8metadata:
9 source: https://skillmd.com/skills/aibot88/myco-mcp-tool-development-lifecycle
10---
11
12# MCP Tool Development and Anti-Drift Maintenance
13
14MCP tools are the primary interface between agents and the Myco intelligence pipeline. Each tool requires a coordinated schema ↔ handler ↔ documentation triad that can drift over time, causing silent agent failures. This skill covers the complete development lifecycle and maintenance procedures to prevent drift regressions.
15
16## Prerequisites
17
18- Working Myco development environment with `packages/myco/src/tools/` structure
19- Understanding of JSON Schema for parameter definitions
20- Familiarity with TypeScript handler patterns and DaemonClient usage
21- Knowledge of local vs cloud MCP bifurcation model
22- Understanding of shared tool-runtime supporting multiple transports (MCP stdio, HTTP MCP, CLI)
23
24## Procedure A: Schema Definition
25
26Define the tool interface in `packages/myco/src/tools/definitions.ts` (shared tool-runtime definitions):
27
281. **Add tool name constant** at the top of the file:
29 ```typescript
30 export const TOOL_MY_NEW_TOOL = 'myco_my_new_tool';
31 ```
32
332. **Add schema entry** to the appropriate array (`TOOL_DEFINITIONS` for local tools, `COLLECTIVE_TOOL_DEFINITIONS` for Collective-dependent tools):
34 ```typescript
35 {
36 name: TOOL_MY_NEW_TOOL,
37 description: 'Brief description of what this tool does — agents use this for selection decisions',
38 cortex: {
39 guidance: 'Clear guidance for when to use this tool vs alternatives',
40 priority: 50, // Default 100, lower numbers = higher priority
41 requiresTeam: false, // Set true if requires team sync
42 requiresCollective: false, // Set true if requires Collective connection
43 },
44 annotations: {
45 readOnlyHint: true, // False if tool mutates state
46 destructiveHint: false, // True if tool can destroy data
47 idempotentHint: true, // False if repeated calls cause different effects
48 openWorldHint: false, // True if tool reaches outside local vault
49 },
50 inputSchema: {
51 type: 'object' as const,
52 properties: {
53 param_name: {
54 type: 'string',
55 description: 'Clear description for agents — include format examples'
56 },
57 optional_param: {
58 type: 'number',
59 description: 'Optional parameter with default behavior explained'
60 }
61 },
62 required: ['param_name']
63 }
64 }
65 ```
66
673. **Use descriptive parameter names** — agents rely on semantic meaning. `session_id` is better than `id`, `batch_limit` is better than `limit`.
68
694. **Document every parameter thoroughly** — the description is what agents use to understand usage. Include examples for complex formats.
70
715. **Set annotations correctly** — `readOnlyHint: true` for read-only tools, `destructiveHint: true` for tools that can destroy data.
72
736. **Configure cortex metadata** — set `requiresCollective: true` for tools that only work when connected to a Collective.
74
757. **Avoid OpenAI strict mode incompatibilities** — OpenAI's strict JSON Schema mode rejects `oneOf`, `anyOf`, `allOf`, `enum`, and `not` keywords at the top level. Use simple types with clear descriptions instead:
76 ```typescript
77 // BAD: OpenAI strict mode rejects this
78 {
79 param_status: {
80 enum: ['active', 'inactive', 'pending'],
81 description: 'Status value'
82 }
83 }
84
85 // GOOD: Use string with enum values in description
86 {
87 param_status: {
88 type: 'string',
89 description: 'Status value. Must be one of: active, inactive, pending'
90 }
91 }
92 ```
93
948. **Avoid Zod refinement-like patterns** — Schema constructs that imply Zod refinements cause silent tool registration failures across runtimes. Never use `.default()`, `.min()`, `.max()`, or `.refine()` patterns in schema definitions:
95 ```typescript
96 // BAD: Implies Zod refinements that cause registration failures
97 {
98 limit: {
99 type: 'number',
100 default: 10, // Zod .default() - causes registration failure
101 minimum: 1, // Zod .min() - causes registration failure
102 maximum: 100 // Zod .max() - causes registration failure
103 }
104 }
105
106 // GOOD: Use plain schema with behavior described in documentation
107 {
108 limit: {
109 type: 'number',
110 description: 'Maximum items to return (1-100, defaults to 10 if omitted)'
111 }
112 }
113 ```
114
115## Procedure B: Handler Implementation
116
117Create the handler in `packages/myco/src/tools/my-new-tool.ts`:
118
1191. **Import required types and client**:
120 ```typescript
121 import type { DaemonClient } from '@myco/hooks/client.js';
122 import { buildEndpoint } from './shared.js';
123 import { ToolFailure } from './error.js';
124 ```
125
1262. **Define input and result types**:
127 ```typescript
128 interface MyNewToolInput {
129 param_name: string;
130 optional_param?: number;
131 }
132
133 interface MyNewToolResult {
134 id: string;
135 status: string;
136 // ... other result fields
137 }
138 ```
139
1403. **Implement the handler function with canonical error handling**:
141 ```typescript
142 export async function handleMyNewTool(
143 input: MyNewToolInput,
144 client: DaemonClient,
145 ): Promise<MyNewToolResult> {
146 // Validate all schema-declared parameters are consumed
147 const { param_name, optional_param = defaultValue } = input;
148
149 try {
150 const endpoint = buildEndpoint('/api/some-operation', {
151 param_name,
152 optional_param,
153 });
154
155 const response = await client.get(endpoint);
156 return response as MyNewToolResult;
157 } catch (error) {
158 // Use ToolFailure for consistent agent-facing error structure
159 throw new ToolFailure(`Failed to execute ${TOOL_MY_NEW_TOOL}`, {
160 cause: error,
161 context: { param_name, optional_param },
162 retriable: true, // Set false for permanent failures
163 });
164 }
165 }
166 ```
167
1684. **Consume every schema parameter** — handlers must accept exactly what the schema advertises. Renamed params, dropped fields, or undocumented required args cause agent call failures.
169
1705. **Use DaemonClient for vault access** — all tools proxy through the daemon HTTP API via `client.get()`, `client.post()`, etc.
171
1726. **Handle errors with ToolFailure interface** — import from `packages/myco/src/tools/error.ts` and wrap operational failures with structured context agents can understand:
173 ```typescript
174 import { ToolFailure } from './error.js';
175
176 // For parameter validation errors
177 throw new ToolFailure('Invalid parameter format', {
178 context: { param_name, expected: 'uuid format' },
179 retriable: false,
180 });
181
182 // For network/service failures
183 throw new ToolFailure('Daemon API unavailable', {
184 cause: originalError,
185 context: { endpoint, attempt: retryCount },
186 retriable: true,
187 });
188 ```
189
1907. **Use canonical ToolFailure interface pattern** — `packages/myco/src/tools/error.ts` exports the standardized `ToolFailure` class with structured error context. Always import and use this interface for agent-facing errors:
191 ```typescript
192 import { ToolFailure, ToolErrorCode } from './error.js';
193
194 // Standard validation failure
195 throw new ToolFailure('Parameter validation failed', {
196 code: ToolErrorCode.INVALID_INPUT,
197 context: { param: value, constraint: 'must be uuid' },
198 retriable: false,
199 });
200
201 // Service availability failure
202 throw new ToolFailure('Daemon service unavailable', {
203 code: ToolErrorCode.SERVICE_UNAVAILABLE,
204 cause: networkError,
205 context: { endpoint, timeout_ms: 5000 },
206 retriable: true,
207 });
208 ```
209
210## Procedure C: Multi-Transport Registration
211
212Register the tool once in the shared tool runtime. Stdio MCP, HTTP MCP, and the CLI all call through `packages/myco/src/tools/index.ts`; do not add transport-specific switch cases for normal tools.
213
2141. **Shared runtime registration** in `packages/myco/src/tools/index.ts`:
215 ```typescript
216 [TOOL_MY_NEW_TOOL, async () => {
217 const { handleMyNewTool } = await import('./my-new-tool.js');
218 return {
219 handle: (input, client) => handleMyNewTool(input as MyNewToolInput, client),
220 summarize: (input, result) => ({ param_name: input.param_name }),
221 };
222 }],
223 ```
224
2252. **MCP stdio and HTTP registration** — `packages/myco/src/mcp/server.ts` exposes the shared definitions from `packages/myco/src/tools/definitions.ts` and dispatches calls through `createMycoTools(...)`.
226
2273. **CLI registration** — `myco tool list` and `myco tool call` use the same shared runtime, so the tool becomes available there after it is in `TOOL_DEFINITIONS` and `HANDLERS`.
228
2294. **Test multi-transport availability** — verify tool appears in MCP client tool list, HTTP MCP endpoints, and CLI help for all configured transports.
230
2315. **Configure conditional enablement** — Collective tools are automatically enabled/disabled based on `collectiveEnabled` flag across all transports. Local tools are always available.
232
233## Procedure D: Documentation Bundling and Regeneration
234
235Each tool carries inline SKILL.md documentation bundled at compile time across all transports:
236
2371. **Write clear tool documentation** covering:
238 - When to use this tool vs alternatives
239 - Parameter meanings and examples
240 - Expected response format
241 - Common usage patterns
242 - Transport-specific considerations (MCP stdio vs HTTP vs CLI)
243
2442. **Bundle at build time** — documentation is compiled into handlers during build process and shared across transports.
245
2463. **Regenerate after schema changes**:
247 ```bash
248 npm run build # Rebuild bundled documentation for all transports
249 ```
250
2514. **Verify agent-visible docs** — test that agents receive current parameter names and descriptions across all transport types, not stale snapshots.
252
2535. **Never ship handler changes without doc updates** — mismatched documentation causes agents to call tools with wrong parameters across any transport.
254
255## Procedure E: Anti-Drift Testing Patterns
256
257Implement systematic checks to catch schema-handler-documentation drift across the shared tool-runtime:
258
2591. **Create test file template** (example: `packages/myco/src/tools/definitions.test.ts`):
260 ```typescript
261 import { describe, test, expect } from 'vitest';
262 import { TOOL_DEFINITIONS, COLLECTIVE_TOOL_DEFINITIONS } from './definitions.js';
263 import * as handlers from './index.js';
264 ```
265
2662. **Schema-handler parameter alignment test**:
267 ```typescript
268 test('all schema parameters referenced in handler source', () => {
269 const allTools = [...TOOL_DEFINITIONS, ...COLLECTIVE_TOOL_DEFINITIONS];
270
271 for (const tool of allTools) {
272 const handlerName = getHandlerNameForTool(tool.name);
273 const handler = handlers[handlerName];
274 if (!handler) continue; // Skip stubs
275
276 const schemaParams = Object.keys(tool.inputSchema.properties || {});
277 const handlerSource = handler.toString();
278
279 schemaParams.forEach(param => {
280 expect(handlerSource).toContain(param);
281 });
282 }
283 });
284 ```
285
2863. **Handler-schema synchronization test**:
287 ```typescript
288 test('no orphaned handler parameters', () => {
289 // Parse handler destructuring patterns, compare to schema
290 // Fail if handler expects parameters not in schema
291 });
292 ```
293
2944. **Tool name constant consistency**:
295 ```typescript
296 test('all tool names match exported constants', () => {
297 const allTools = [...TOOL_DEFINITIONS, ...COLLECTIVE_TOOL_DEFINITIONS];
298
299 allTools.forEach(tool => {
300 expect(tool.name).toMatch(/^(myco_|collective_)/);
301 // Verify constant exists and matches
302 });
303 });
304 ```
305
3065. **Multi-transport registration consistency**:
307 ```typescript
308 test('all tools registered across transports', () => {
309 // Verify MCP stdio, HTTP MCP, and CLI registrations are consistent
310 // Check that transport-specific configurations align with shared definitions
311 });
312 ```
313
3146. **Run after every handler or schema change** — drift failures are silent until agents encounter them in production across any transport.
315
316## Procedure F: Stub vs Documented Tool Discipline
317
318Handle incomplete or placeholder tools appropriately:
319
3201. **Mark stubs explicitly** in schema description:
321 ```typescript
322 {
323 name: TOOL_MY_STUB,
324 description: '[STUB] This tool is registered but not yet implemented. Returns placeholder response only.',
325 // ... rest of definition
326 }
327 ```
328
3292. **Implement stub handlers** that return consistent "not implemented" responses:
330 ```typescript
331 export async function handleMyStub(): Promise<{ status: string }> {
332 return { status: 'not_implemented' };
333 }
334 ```
335
3363. **Never document stubs as working tools** — agents should know when functionality is incomplete across all transports.
337
3384. **Test stub behavior** — ensure stubs return consistent responses rather than errors across MCP stdio, HTTP MCP, and CLI.
339
3405. **Remove or implement** — stubs confuse agents across all transports. Either complete the implementation or remove from schema entirely.
341
342## Procedure G: Cloud vs Local Placement Decisions
343
344Decide whether new tools belong in local or cloud MCP surface:
345
3461. **Default to local-only** — new tools go in `TOOL_DEFINITIONS` unless they meet cloud criteria.
347
3482. **Promote to cloud surface** only if tool is:
349 - Semantically read-only (no vault writes)
350 - Safe for federation (no sensitive data exposure)
351 - Required for cross-project Collective operations
352
3533. **Use `COLLECTIVE_TOOL_DEFINITIONS`** for tools that require Collective connection state.
354
3554. **Test both surfaces** — verify tools work correctly in local MCP and (if applicable) cloud federation.
356
3575. **Document placement rationale** — explain why tool belongs in its chosen surface.
358
359## Procedure H: Skill Lifecycle Tool Registration Patterns
360
361The skill lifecycle system requires specific tools that follow domain-specific registration patterns:
362
3631. **Register skill candidate management tools**:
364 ```typescript
365 // In packages/myco/src/tools/definitions.ts
366 export const TOOL_SKILL_CANDIDATES = 'myco_skill_candidates';
367
368 {
369 name: TOOL_SKILL_CANDIDATES,
370 description: 'Manage skill candidates (identified topics that may become skills). Supports list, get, create, and update actions.',
371 cortex: {
372 guidance: 'Use for candidate discovery, approval workflows, and candidate lifecycle management',
373 priority: 80,
374 requiresTeam: false,
375 requiresCollective: false,
376 },
377 annotations: {
378 readOnlyHint: false,
379 destructiveHint: false,
380 idempotentHint: false,
381 openWorldHint: false,
382 },
383 inputSchema: {
384 type: 'object',
385 properties: {
386 action: {
387 type: 'string',
388 description: 'Action to perform: list, get, create, update, delete'
389 },
390 id: {
391 type: 'string',
392 description: 'Candidate ID (required for get/update)'
393 },
394 topic: {
395 type: 'string',
396 description: 'Skill topic (required for create)'
397 },
398 rationale: {
399 type: 'string',
400 description: 'Why this should be a skill (required for create)'
401 },
402 status: {
403 type: 'string',
404 description: 'Candidate status: identified, dismissed'
405 }
406 },
407 required: ['action']
408 }
409 }
410 ```
411
4122. **Register skill record management tools**:
413 ```typescript
414 export const TOOL_SKILL_RECORDS = 'myco_skill_records';
415
416 {
417 name: TOOL_SKILL_RECORDS,
418 description: 'Read, update, and delete skill records (materialized skills on disk). Supports list, get, update, and delete actions.',
419 cortex: {
420 guidance: 'Use for skill lifecycle operations — reading existing skills, updating status, managing skill evolution',
421 priority: 80,
422 },
423 inputSchema: {
424 type: 'object',
425 properties: {
426 action: { type: 'string', description: 'Action: list, get, update, delete' },
427 id: { type: 'string', description: 'Skill record ID or name (for get/update/delete)' },
428 status: { type: 'string', description: 'Filter by or new status: active, stale, retired' },
429 generation: { type: 'number', description: 'New generation number (for update)' }
430 },
431 required: ['action']
432 }
433 }
434 ```
435
4363. **Register skill file writing tools**:
437 ```typescript
438 export const TOOL_WRITE_SKILL = 'myco_write_skill';
439
440 {
441 name: TOOL_WRITE_SKILL,
442 description: 'Write a SKILL.md file to disk and create or update the corresponding skill record and lineage entry.',
443 cortex: {
444 guidance: 'Use when materializing a new skill from approved candidates or updating existing skills',
445 priority: 90,
446 },
447 annotations: {
448 readOnlyHint: false,
449 destructiveHint: false,
450 idempotentHint: false,
451 openWorldHint: false,
452 },
453 inputSchema: {
454 type: 'object',
455 properties: {
456 name: { type: 'string', description: 'Skill directory name (kebab-case, NO colon)' },
457 display_name: { type: 'string', description: 'Human-readable display name' },
458 description: { type: 'string', description: 'Short description of what the skill does' },
459 content: { type: 'string', description: 'Full SKILL.md content in markdown' },
460 rationale: { type: 'string', description: 'Why this skill was created or updated' },
461 candidate_id: { type: 'string', description: 'Candidate ID that prompted this skill creation' }
462 },
463 required: ['name', 'display_name', 'description', 'content']
464 }
465 }
466 ```
467
4684. **Implement domain-specific validation patterns** — skill tools require structural validation (YAML frontmatter, name prefixes, content length limits) that differs from general vault tools.
469
4705. **Test skill workflow integration** — verify tools support the complete skill lifecycle: survey → approve → generate → evolve.
471
472## Procedure I: Shared Tool-Runtime Integration
473
474Integrate with the shared tool-runtime supporting multiple transports:
475
4761. **Configure transport-specific behaviors**:
477 ```typescript
478 // Different transports may need different error handling
479 const formatResponse = (result: any, transport: 'mcp' | 'http' | 'cli') => {
480 switch (transport) {
481 case 'mcp': return { content: [{ type: 'text', text: JSON.stringify(result, null, 2) }] };
482 case 'http': return result; // Direct JSON response
483 case 'cli': return formatCliOutput(result); // Human-readable format
484 }
485 };
486 ```
487
4882. **Handle transport-specific authentication** — MCP stdio uses connection-level auth, HTTP MCP uses token auth, CLI uses file-based auth.
489
4903. **Implement transport-aware logging**:
491 ```typescript
492 logActivity(TOOL_NAME, {
493 ...params,
494 transport: 'mcp|http|cli',
495 duration_ms: Date.now() - start
496 });
497 ```
498
4994. **Test cross-transport consistency** — verify same input produces equivalent results across MCP stdio, HTTP MCP, and CLI transports.
500
5015. **Document transport differences** — note any transport-specific behaviors or limitations in tool documentation.
502
503## Procedure J: Grove Migration Context Handling
504
505Handle project context changes with Grove migration architecture:
506
5071. **Update context injection patterns** for Grove migration compatibility:
508 ```typescript
509 // Old: Direct project context injection
510 const context = await injectProjectContext(sessionId);
511
512 // New: Grove-aware context injection with fallback
513 const context = await injectGroveContext(sessionId, {
514 fallbackToLocal: true,
515 respectGroveConfig: true,
516 });
517 ```
518
5192. **Handle Grove project boundaries** when tools access cross-project resources:
520 ```typescript
521 export async function handleCrossProjectTool(
522 input: CrossProjectInput,
523 client: DaemonClient,
524 ): Promise<CrossProjectResult> {
525 // Validate Grove project permissions before access
526 const groveAccess = await client.get('/api/grove/validate-access', {
527 targetProject: input.project_id,
528 operation: 'read',
529 });
530
531 if (!groveAccess.allowed) {
532 throw new ToolFailure('Grove access denied', {
533 context: { project_id: input.project_id, reason: groveAccess.reason },
534 retriable: false,
535 });
536 }
537
538 // Proceed with Grove-scoped operation
539 return await performGroveOperation(input, client);
540 }
541 ```
542
5433. **Configure Grove-aware tool definitions** with proper scope annotations:
544 ```typescript
545 {
546 name: TOOL_GROVE_AWARE,
547 description: 'Tool that operates across Grove project boundaries',
548 cortex: {
549 guidance: 'Use for cross-project operations in Grove environments',
550 requiresGrove: true, // New Grove requirement flag
551 },
552 annotations: {
553 crossProjectHint: true, // Indicates Grove boundary crossing
554 },
555 }
556 ```
557
5584. **Test Grove project isolation** — verify tools respect Grove project boundaries and fail gracefully when Grove is not configured.
559
5605. **Document Grove migration impact** — note how tools behave differently in Grove vs traditional project structures.
561
562## Cross-Cutting Gotchas
563
564**Silent parameter drops**: When schema defines a parameter but handler ignores it, agents receive no error — their input is silently dropped. This is the most common drift failure.
565
566**Documentation lag**: Bundled SKILL.md becomes stale when handlers change. Always regenerate documentation after schema or handler modifications.
567
568**Cloud surface leakage**: Write operations must never leak to cloud MCP surface. Default to local-only; promote to cloud only with explicit read-only verification.
569
570**Validation vs runtime divergence**: Schema validation passes but handler expects different parameter structure. Test actual invocations, not just schema validation.
571
572**Collective conditional enablement**: `collective_*` tools are enabled by Collective connection state. Test both connected and disconnected scenarios across all transports.
573
574**Tool name consistency**: Use `myco_` prefix for standard tools, `collective_` prefix for Collective-dependent tools. Avoid generic names that conflict with other MCP servers.
575
576**Handler signature mismatch**: All handlers must accept `(input, client)` parameters. Missing DaemonClient parameter causes registration failures.
577
578**Cross-runtime schema compatibility**: OpenAI strict mode and Zod refinement patterns cause silent registration failures. Use plain JSON Schema types with descriptive documentation instead of complex validation constructs.
579
580**Skill tool registration gaps**: Skill lifecycle operations require complete tool registration (candidates, records, write_skill) — missing any component breaks agent workflows. Always register skill tools as a complete set.
581
582**Shared tool-runtime path shifts**: Tool definitions live in `packages/myco/src/tools/definitions.ts`. Update import paths and test references when the shared runtime moves.
583
584**Multi-transport registration complexity**: Shared tool-runtime requires consistent registration across MCP stdio, HTTP MCP, and CLI transports. Test all transports when adding new tools.
585
586**Transport-specific error handling**: Different transports expect different response formats. Implement transport-aware error formatting to prevent agent confusion.
587
588**ToolFailure anti-pattern**: Never throw raw Error objects from handlers — always wrap with ToolFailure interface for consistent agent error handling. Missing structured error context causes agent confusion across all transports.
589
590**Code duplication across tool surface**: Avoid copy-pasting handler patterns between tools. Extract shared utilities to `packages/myco/src/tools/shared.ts` and import consistently. Duplicated validation logic, error handling, and response formatting patterns create maintenance burden and drift risks across the unified tool surface. Use composition patterns instead:
591```typescript
592// BAD: Duplicated validation across multiple tools
593function handleToolA(input) {
594 if (!input.session_id || !isValidUuid(input.session_id)) {
595 throw new ToolFailure('Invalid session_id');
596 }
597 // ... tool logic
598}
599
600function handleToolB(input) {
601 if (!input.session_id || !isValidUuid(input.session_id)) {
602 throw new ToolFailure('Invalid session_id');
603 }
604 // ... tool logic (nearly identical validation)
605}
606
607// GOOD: Shared validation utilities
608import { validateSessionId, validateRequiredString } from './shared.js';
609
610function handleToolA(input) {
611 validateSessionId(input.session_id);
612 // ... tool logic
613}
614
615function handleToolB(input) {
616 validateSessionId(input.session_id);
617 // ... tool logic
618}
619```
620
621**Grove context injection failures**: Tools accessing project context must handle Grove migration gracefully. Missing Grove-aware context injection causes failures in Grove environments while working in traditional project structures, creating environment-specific bugs.