Skip to main content
Glama

comment_contract

Add cross-reference comments to validated producer/consumer pairs to document contract relationships in both source files.

Instructions

Add cross-reference comments to validated producer/consumer pairs. Documents the contract relationship in both files.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
producerDirYesPath to MCP server source directory
consumerDirYesPath to consumer source directory
toolNameYesName of the validated tool
dryRunNoPreview comments without writing to files (default: true)
styleNoComment style

Implementation Reference

  • Primary handler for the 'comment_contract' MCP tool. Parses input, extracts schemas from producer and consumer directories, validates the tool exists in both, prepares options, and dispatches to previewContractComments (dryRun) or addContractComments.
    case 'comment_contract': {
      const input = CommentContractInput.parse(args);
      log(`Commenting contract for tool: ${input.toolName}`);
      
      // Get both producer and consumer
      const producers = await extractProducerSchemas({ rootDir: input.producerDir });
      const consumers = await traceConsumerUsage({ rootDir: input.consumerDir });
      
      const producer = producers.find(p => p.toolName === input.toolName);
      const consumer = consumers.find(c => c.toolName === input.toolName);
      
      if (!producer) {
        throw new Error(`Tool "${input.toolName}" not found in producer at ${input.producerDir}`);
      }
      if (!consumer) {
        throw new Error(`Tool "${input.toolName}" not found in consumer at ${input.consumerDir}`);
      }
      
      const match = {
        toolName: input.toolName,
        producerLocation: producer.location,
        consumerLocation: consumer.callSite,
      };
      
      const commentOptions = {
        match,
        producer,
        consumer,
        style: input.style || 'block' as const,
        includeTimestamp: true,
      };
      
      if (input.dryRun !== false) {
        // Preview mode (default)
        const preview = previewContractComments(commentOptions);
        
        return {
          content: [
            {
              type: 'text',
              text: JSON.stringify({
                success: true,
                mode: 'preview',
                toolName: input.toolName,
                producerPreview: preview.producerPreview,
                consumerPreview: preview.consumerPreview,
                note: 'Set dryRun: false to actually add these comments to files',
              }, null, 2),
            },
          ],
        };
      } else {
        // Actually add comments
        const result = await addContractComments(commentOptions);
        
        return {
          content: [
            {
              type: 'text',
              text: JSON.stringify({
                success: result.success,
                mode: 'applied',
                toolName: input.toolName,
                producerFile: result.producerFile,
                consumerFile: result.consumerFile,
                producerComment: result.producerComment,
                consumerComment: result.consumerComment,
                error: result.error,
              }, null, 2),
            },
          ],
        };
      }
    }
  • Zod schema defining the input parameters for the comment_contract tool.
    const CommentContractInput = z.object({
      producerDir: z.string().describe('Path to MCP server source directory'),
      consumerDir: z.string().describe('Path to consumer source directory'),
      toolName: z.string().describe('Name of the validated tool'),
      dryRun: z.boolean().optional().describe('Preview comments without writing to files (default: true)'),
      style: z.enum(['jsdoc', 'inline', 'block']).optional().describe('Comment style (default: block)'),
    });
  • src/index.ts:221-235 (registration)
    Registration of the comment_contract tool in the ListToolsRequest handler, providing name, description, and input schema.
    {
      name: 'comment_contract',
      description: 'Add cross-reference comments to validated producer/consumer pairs. Documents the contract relationship in both files.',
      inputSchema: {
        type: 'object',
        properties: {
          producerDir: { type: 'string', description: 'Path to MCP server source directory' },
          consumerDir: { type: 'string', description: 'Path to consumer source directory' },
          toolName: { type: 'string', description: 'Name of the validated tool' },
          dryRun: { type: 'boolean', description: 'Preview comments without writing to files (default: true)' },
          style: { type: 'string', enum: ['jsdoc', 'inline', 'block'], description: 'Comment style' },
        },
        required: ['producerDir', 'consumerDir', 'toolName'],
      },
    },
  • Core implementation for adding contract comments to source files using ts-morph. Loads files, inserts comments before relevant nodes (tool definition and callTool), and saves changes.
    export async function addContractComments(options: ContractCommentOptions): Promise<CommentResult> {
      const { match, producer, consumer } = options;
      const { producerComment, consumerComment } = generateContractComments(options);
      
      const project = new Project({
        skipAddingFilesFromTsConfig: true,
      });
    
      try {
        // Add comment to producer file
        const producerFile = project.addSourceFileAtPath(producer.location.file);
        const producerNode = findNodeAtLine(producerFile, producer.location.line);
        
        if (producerNode) {
          // Add comment before the tool definition
          producerNode.replaceWithText(`${producerComment}\n${producerNode.getText()}`);
        }
    
        // Add comment to consumer file
        const consumerFile = project.addSourceFileAtPath(consumer.callSite.file);
        const consumerNode = findNodeAtLine(consumerFile, consumer.callSite.line);
        
        if (consumerNode) {
          // Add comment before the callTool invocation
          consumerNode.replaceWithText(`${consumerComment}\n${consumerNode.getText()}`);
        }
    
        // Save changes
        await project.save();
    
        return {
          success: true,
          producerFile: producer.location.file,
          consumerFile: consumer.callSite.file,
          producerComment,
          consumerComment,
        };
      } catch (error) {
        return {
          success: false,
          producerFile: producer.location.file,
          consumerFile: consumer.callSite.file,
          producerComment,
          consumerComment,
          error: error instanceof Error ? error.message : String(error),
        };
      }
    }
  • Generates the actual comment strings for producer and consumer, formatting details like file locations, args/props used, and validation timestamp.
    export function generateContractComments(options: ContractCommentOptions): {
      producerComment: string;
      consumerComment: string;
    } {
      const { match, producer, consumer, style = 'block', includeTimestamp = true, prefix = '@trace-contract' } = options;
      const timestamp = includeTimestamp ? ` | Validated: ${new Date().toISOString().split('T')[0]}` : '';
      
      // Producer comment points to consumer
      const producerComment = formatComment({
        style,
        lines: [
          `${prefix} PRODUCER`,
          `Tool: ${match.toolName}`,
          `Consumer: ${consumer.callSite.file}:${consumer.callSite.line}`,
          `Args: ${Object.keys(consumer.argumentsProvided).join(', ')}`,
          `Expected Props: ${consumer.expectedProperties.slice(0, 5).join(', ')}${consumer.expectedProperties.length > 5 ? '...' : ''}`,
          timestamp ? `Validated: ${timestamp}` : '',
        ].filter(Boolean),
      });
    
      // Consumer comment points to producer  
      const consumerComment = formatComment({
        style,
        lines: [
          `${prefix} CONSUMER`,
          `Tool: ${match.toolName}`,
          `Producer: ${producer.location.file}:${producer.location.line}`,
          `Required Args: ${producer.inputSchema.required?.join(', ') || 'none'}`,
          `Schema Props: ${Object.keys(producer.inputSchema.properties || {}).join(', ')}`,
          timestamp ? `Validated: ${timestamp}` : '',
        ].filter(Boolean),
      });
    
      return { producerComment, consumerComment };
    }
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations are provided, so the description carries the full burden of behavioral disclosure. It mentions adding comments and documenting relationships, but fails to describe critical behaviors: whether this modifies files (implied but not explicit), what permissions or side effects are involved, error handling, or output format. For a tool that likely writes to files, this is a significant gap in transparency.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is concise and front-loaded, consisting of two clear sentences that directly state the tool's purpose and outcome. There is no wasted language, though it could be slightly more structured by explicitly separating action from context. Overall, it is efficient and easy to parse.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the complexity of a tool with 5 parameters, no annotations, and no output schema, the description is incomplete. It lacks details on behavioral traits (e.g., file modifications, error handling), usage context, and output expectations. While the schema covers parameters, the description does not compensate for the absence of annotations or output schema, leaving significant gaps for the agent.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 100%, so the schema fully documents all parameters. The description adds no additional meaning beyond what the schema provides—it does not explain how 'producerDir' and 'consumerDir' relate to the commenting process or clarify the purpose of 'toolName' in context. Baseline 3 is appropriate as the schema does the heavy lifting.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the specific action ('Add cross-reference comments'), the target ('validated producer/consumer pairs'), and the outcome ('Documents the contract relationship in both files'). It uses precise verbs and distinguishes itself from siblings like 'compare' or 'trace_usage' by focusing on documentation through comments rather than analysis or tracing.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides no guidance on when to use this tool versus alternatives. It mentions 'validated producer/consumer pairs' but does not specify how validation occurs, what prerequisites are needed, or when to choose this over other tools like 'scaffold_consumer' or 'trace_file'. Without such context, the agent lacks clear usage instructions.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/Mnehmos/trace-mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server