Files
claude-task-master/mcp-server/src/custom-sdk/schema-converter.js
Oren Me b53065713c feat: add support for MCP Sampling as AI provider (#863)
* feat: support MCP sampling

* support provider registry

* use standard config options for MCP provider

* update fastmcp to support passing params to requestSampling

* move key name definition to base provider

* moved check for required api key to provider class

* remove unused code

* more cleanup

* more cleanup

* refactor provider

* remove not needed files

* more cleanup

* more cleanup

* more cleanup

* update docs

* fix tests

* add tests

* format fix

* clean files

* merge fixes

* format fix

* feat: add support for MCP Sampling as AI provider

* initial mcp ai sdk

* fix references to old provider

* update models

* lint

* fix gemini-cli conflicts

* ran format

* Update src/provider-registry/index.js

Co-authored-by: Ralph Khreish <35776126+Crunchyman-ralph@users.noreply.github.com>

* fix circular dependency

Circular Dependency Issue  FIXED
Root Cause: BaseAIProvider was importing from index.js, which includes commands.js and other modules that eventually import back to AI providers
Solution: Changed imports to use direct paths to avoid circular dependencies:
Updated base-provider.js to import log directly from utils.js
Updated gemini-cli.js to import log directly from utils.js
Result: Fixed 11 failing tests in mcp-provider.test.js

* fix gemini test

* fix(claude-code): recover from CLI JSON truncation bug (#913) (#920)

Gracefully handle SyntaxError thrown by @anthropic-ai/claude-code when the CLI truncates large JSON outputs (4–16 kB cut-offs).\n\nKey points:\n• Detect JSON parse error + existing buffered text in both doGenerate() and doStream() code paths.\n• Convert the failure into a recoverable 'truncated' finish state and push a provider-warning.\n• Allows Task Master to continue parsing long PRDs / expand-task operations instead of crashing.\n\nA patch changeset (.changeset/claude-code-json-truncation.md) is included for the next release.\n\nRef: eyaltoledano/claude-task-master#913

* docs: fix gemini-cli authentication documentation (#923)

Remove erroneous 'gemini auth login' command references and replace with correct 'gemini' command authentication flow. Update documentation to reflect proper OAuth setup process via the gemini CLI interactive interface.

* fix tests

* fix: update ai-sdk-provider-gemini-cli to 0.0.4 for improved authentication (#932)

- Fixed authentication compatibility issues with Google auth
- Added support for 'api-key' auth type alongside 'gemini-api-key'
- Resolved "Unsupported authType: undefined" runtime errors
- Updated @google/gemini-cli-core dependency to 0.1.9
- Improved documentation and removed invalid auth references
- Maintained backward compatibility while enhancing type validation

* call logging directly

Need to patch upstream fastmcp to allow easier access and bootstrap the TM mcp logger to use the fastmcp logger which today is only exposed in the tools handler

* fix tests

* removing logs until we figure out how to pass mcp logger

* format

* fix tests

* format

* clean up

* cleanup

* readme fix

---------

Co-authored-by: Oren Melamed <oren.m@gloat.com>
Co-authored-by: Ralph Khreish <35776126+Crunchyman-ralph@users.noreply.github.com>
Co-authored-by: Ben Vargas <ben@vargas.com>
2025-07-09 10:54:38 +02:00

151 lines
4.0 KiB
JavaScript

/**
* @fileoverview Schema conversion utilities for MCP AI SDK provider
*/
/**
* Convert Zod schema to human-readable JSON instructions
* @param {import('zod').ZodSchema} schema - Zod schema object
* @param {string} [objectName='result'] - Name of the object being generated
* @returns {string} Instructions for JSON generation
*/
export function convertSchemaToInstructions(schema, objectName = 'result') {
try {
// Generate example structure from schema
const exampleStructure = generateExampleFromSchema(schema);
return `
CRITICAL JSON GENERATION INSTRUCTIONS:
You must respond with ONLY valid JSON that matches this exact structure for "${objectName}":
${JSON.stringify(exampleStructure, null, 2)}
STRICT REQUIREMENTS:
1. Response must start with { and end with }
2. Use double quotes for all strings and property names
3. Do not include any text before or after the JSON
4. Do not wrap in markdown code blocks
5. Do not include explanations or comments
6. Follow the exact property names and types shown above
7. All required fields must be present
Begin your response immediately with the opening brace {`;
} catch (error) {
// Fallback to basic JSON instructions if schema parsing fails
return `
CRITICAL JSON GENERATION INSTRUCTIONS:
You must respond with ONLY valid JSON for "${objectName}".
STRICT REQUIREMENTS:
1. Response must start with { and end with }
2. Use double quotes for all strings and property names
3. Do not include any text before or after the JSON
4. Do not wrap in markdown code blocks
5. Do not include explanations or comments
Begin your response immediately with the opening brace {`;
}
}
/**
* Generate example structure from Zod schema
* @param {import('zod').ZodSchema} schema - Zod schema
* @returns {any} Example object matching the schema
*/
function generateExampleFromSchema(schema) {
// This is a simplified schema-to-example converter
// For production, you might want to use a more sophisticated library
if (!schema || typeof schema._def === 'undefined') {
return {};
}
const def = schema._def;
switch (def.typeName) {
case 'ZodObject':
const result = {};
const shape = def.shape();
for (const [key, fieldSchema] of Object.entries(shape)) {
result[key] = generateExampleFromSchema(fieldSchema);
}
return result;
case 'ZodString':
return 'string';
case 'ZodNumber':
return 0;
case 'ZodBoolean':
return false;
case 'ZodArray':
const elementExample = generateExampleFromSchema(def.type);
return [elementExample];
case 'ZodOptional':
return generateExampleFromSchema(def.innerType);
case 'ZodNullable':
return generateExampleFromSchema(def.innerType);
case 'ZodEnum':
return def.values[0] || 'enum_value';
case 'ZodLiteral':
return def.value;
case 'ZodUnion':
// Use the first option from the union
if (def.options && def.options.length > 0) {
return generateExampleFromSchema(def.options[0]);
}
return 'union_value';
case 'ZodRecord':
return {
key: generateExampleFromSchema(def.valueType)
};
default:
// For unknown types, return a placeholder
return `<${def.typeName || 'unknown'}>`;
}
}
/**
* Enhance prompt with JSON generation instructions
* @param {Array} prompt - AI SDK prompt array
* @param {string} jsonInstructions - JSON generation instructions
* @returns {Array} Enhanced prompt array
*/
export function enhancePromptForJSON(prompt, jsonInstructions) {
const enhancedPrompt = [...prompt];
// Find system message or create one
let systemMessageIndex = enhancedPrompt.findIndex(
(msg) => msg.role === 'system'
);
if (systemMessageIndex >= 0) {
// Append to existing system message
const currentContent = enhancedPrompt[systemMessageIndex].content;
enhancedPrompt[systemMessageIndex] = {
...enhancedPrompt[systemMessageIndex],
content: currentContent + '\n\n' + jsonInstructions
};
} else {
// Add new system message at the beginning
enhancedPrompt.unshift({
role: 'system',
content: jsonInstructions
});
}
return enhancedPrompt;
}