Skip to main content
Glama
mdz-axo

PT-MCP (Paul Test Man Context Protocol)

by mdz-axo

generate_context

Create context files in various formats from codebases to help AI assistants understand project structure and dependencies.

Instructions

Generate context files in specified format for the codebase

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
pathYesRoot directory path
formatYesContext file format to generate
output_pathNoOutput path for generated files (optional)
analysis_resultNoPrevious analysis result to use (optional)
optionsNoFormat-specific options

Implementation Reference

  • Main handler function that executes the generate_context tool logic: analyzes codebase if needed, optionally enriches with KG, generates format-specific context content, writes to file if specified, and returns success response.
    export async function generateContext(
      args: GenerateContextArgs
    ): Promise<{ content: Array<{ type: string; text: string }> }> {
      const { path, format, output_path, analysis_result, options = {} } = args;
    
      // Get or perform analysis
      let analysis = analysis_result;
      if (!analysis) {
        const analyzeResult = await analyzeCodebase({ path });
        analysis = JSON.parse(analyzeResult.content[0].text);
      }
    
      // Enrich with knowledge graph if enabled (default: true)
      let enriched: EnrichedContext | null = null;
      if (options.enable_kg !== false) {
        enriched = await enrichContext({
          path,
          analysis_result: analysis,
          enrichment_level: options.enrichment_level || 'standard',
          include_yago: options.include_yago !== false,
          include_schema: options.include_schema !== false,
          max_entities: options.max_entities || 10,
        });
      }
    
      // Generate context based on format
      let content: string;
      let filename: string;
    
      switch (format) {
        case 'cursorrules':
          content = generateCursorRules(analysis, enriched);
          filename = '.cursorrules';
          break;
    
        case 'cursor_dir':
          content = generateCursorDir(analysis, enriched);
          filename = '.cursor/context.md';
          break;
    
        case 'spec_md':
          content = generateSpecMd(analysis, enriched);
          filename = 'SPEC.md';
          break;
    
        case 'agents_md':
          content = generateAgentsMd(analysis, enriched);
          filename = 'AGENTS.md';
          break;
    
        case 'custom':
          content = generateCustom(analysis, enriched, options);
          filename = options.filename || 'context.md';
          break;
    
        default:
          throw new Error(`Unknown format: ${format}`);
      }
    
      // Write to file if output_path specified
      if (output_path) {
        const fullPath = join(output_path, filename);
        const dir = dirname(fullPath);
    
        if (!existsSync(dir)) {
          await mkdir(dir, { recursive: true });
        }
    
        await writeFile(fullPath, content, 'utf-8');
      }
    
      return {
        content: [
          {
            type: 'text',
            text: JSON.stringify(
              {
                message: 'Context generated successfully',
                format,
                path,
                output_file: output_path ? join(output_path, filename) : null,
                content_preview: content.slice(0, 500) + '...',
                enriched: !!enriched,
                kg_stats: enriched?.confidence_stats,
              },
              null,
              2
            ),
          },
        ],
      };
    }
  • TypeScript interface defining the input arguments for the generateContext handler.
    interface GenerateContextArgs {
      path: string;
      format: 'cursorrules' | 'cursor_dir' | 'spec_md' | 'agents_md' | 'custom';
      output_path?: string;
      analysis_result?: any;
      options?: Record<string, any>;
    }
  • Tool dispatch/registration in the switch statement handling CallToolRequestSchema, calling generateContext for "generate_context".
    case "generate_context":
      return await generateContext(args as any);
  • src/index.ts:140-169 (registration)
    Tool registration in ListToolsRequestSchema response, defining name, description, and inputSchema for MCP protocol compliance.
      name: "generate_context",
      description: "Generate context files in specified format for the codebase",
      inputSchema: {
        type: "object",
        properties: {
          path: {
            type: "string",
            description: "Root directory path",
          },
          format: {
            type: "string",
            enum: ["cursorrules", "cursor_dir", "spec_md", "agents_md", "custom"],
            description: "Context file format to generate",
          },
          output_path: {
            type: "string",
            description: "Output path for generated files (optional)",
          },
          analysis_result: {
            type: "object",
            description: "Previous analysis result to use (optional)",
          },
          options: {
            type: "object",
            description: "Format-specific options",
          },
        },
        required: ["path", "format"],
      },
    },
  • Helper function to generate content in '.cursorrules' format, one of several format-specific generators used by the handler.
    function generateCursorRules(analysis: any, enriched: EnrichedContext | null): string {
      const lines: string[] = [];
    
      lines.push('# Project Rules for AI Assistants');
      lines.push('');
    
      // Project info
      if (analysis.package?.name) {
        lines.push(`## Project: ${analysis.package.name}`);
        if (analysis.package.description) {
          lines.push(analysis.package.description);
        }
        lines.push('');
      }
    
      // Schema.org annotation
      if (enriched?.schema_annotation) {
        lines.push('## Semantic Type');
        lines.push(`This is a **${enriched.schema_annotation['@type']}**`);
        if (enriched.schema_annotation.description) {
          lines.push(enriched.schema_annotation.description);
        }
        lines.push('');
      }
    
      // Tech stack
      lines.push('## Tech Stack');
      if (analysis.languages) {
        lines.push('**Languages:**', Object.keys(analysis.languages).join(', '));
      }
      if (analysis.frameworks && analysis.frameworks.length > 0) {
        lines.push('**Frameworks:**', analysis.frameworks.join(', '));
      }
      lines.push('');
    
      // Knowledge graph enrichment
      if (enriched?.yago_entities && Object.keys(enriched.yago_entities).length > 0) {
        lines.push('## Knowledge Graph Context');
        for (const [name, entities] of Object.entries(enriched.yago_entities)) {
          if (entities.length > 0) {
            const entity = entities[0];
            lines.push(`- **${name}**: ${entity.description || entity.label}`);
          }
        }
        lines.push('');
      }
    
      // Coding conventions
      lines.push('## Coding Conventions');
      lines.push('- Follow existing patterns in the codebase');
      lines.push('- Use TypeScript strict mode');
      lines.push('- Write clear, self-documenting code');
      lines.push('- Add JSDoc comments for public APIs');
      lines.push('');
    
      return lines.join('\n');
    }
Behavior2/5

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

No annotations are provided, so the description carries full burden. It states what the tool does but doesn't disclose behavioral traits like whether it overwrites existing files, requires specific permissions, has side effects on the codebase, or handles errors. For a tool that generates files (potentially destructive), this lack of transparency is a significant gap.

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 a single, efficient sentence that front-loads the core purpose. There's no wasted verbiage or redundancy. However, it could be slightly more informative by hinting at the tool's role in a workflow (e.g., 'Generate context files... to summarize codebase structure').

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 5 parameters, no annotations, no output schema, and siblings with overlapping functions, the description is incomplete. It doesn't clarify the tool's place in the workflow (e.g., after analysis), what 'context files' are used for, or behavioral risks. For a file-generation tool with potential side effects, more context is needed.

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 5 parameters. The description adds no additional meaning beyond implying 'path' is for the codebase and 'format' specifies the output type. It doesn't explain what 'context files' contain, how 'analysis_result' integrates, or what 'options' might include. 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.

Purpose4/5

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

The description clearly states the action ('generate') and resource ('context files') with the scope ('for the codebase') and format specification. It distinguishes from siblings like 'analyze_codebase' or 'update_context' by focusing on file generation rather than analysis or modification. However, it doesn't explicitly differentiate from 'enrich_context' or 'validate_context' which might have overlapping purposes.

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 like 'enrich_context', 'update_context', or 'validate_context'. It doesn't mention prerequisites (e.g., needing an analyzed codebase first) or exclusions (e.g., not for real-time monitoring). The agent must infer usage from the tool name and parameters alone.

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/mdz-axo/pt-mcp'

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