Skip to main content
Glama
mdz-axo

PT-MCP (Paul Test Man Context Protocol)

by mdz-axo

enrich_context

Enhance codebase understanding by integrating YAGO knowledge graph data and Schema.org semantic annotations to provide contextual insights about project structure and relationships.

Instructions

Enrich codebase context with knowledge graph data from YAGO 4.5 and Schema.org annotations

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
pathYesRoot directory path
analysis_resultNoPrevious analysis result from analyze_codebase (optional)
enrichment_levelNoLevel of enrichment (minimal: frameworks+languages, standard: +dependencies, comprehensive: +dev deps+patterns)standard
include_yagoNoInclude YAGO knowledge graph entity linking
include_schemaNoInclude Schema.org semantic annotations
max_entitiesNoMaximum entities to resolve from YAGO

Implementation Reference

  • Core handler function that executes the enrich_context tool logic: extracts entities, resolves YAGO knowledge graph entities, applies Schema.org annotations, computes confidence stats, and generates structured metadata.
    export async function enrichContext(args: EnrichContextArgs): Promise<EnrichedContext> {
      const {
        path,
        analysis_result,
        enrichment_level = 'standard',
        include_yago = true,
        include_schema = true,
        max_entities = 10,
      } = args;
    
      const result: EnrichedContext = {
        path,
        enrichment_metadata: {
          level: enrichment_level,
          timestamp: new Date().toISOString(),
          cache_hits: 0,
          yago_queries: 0,
        },
      };
    
      // If no analysis provided, we can only do minimal enrichment
      if (!analysis_result) {
        return {
          ...result,
          yago_entities: {},
          schema_annotation: {},
          json_ld: {},
        };
      }
    
      const db = await getDatabase();
      const yagoResolver = getYAGOResolver();
      const schemaMapper = getSchemaMapper();
    
      // Extract entities from analysis
      const entities = extractEntitiesFromAnalysis(analysis_result, enrichment_level);
    
      // YAGO enrichment
      if (include_yago) {
        const yagoEntities: { [key: string]: YAGOEntity[] } = {};
        let cacheHits = 0;
        let yagoQueries = 0;
    
        for (const [name, type] of entities.slice(0, max_entities)) {
          try {
            // Check if already cached
            const entity = db.findEntityByName(name);
            if (entity?.id) {
              const mapping = db.findYAGOMappingByEntityId(entity.id);
              if (mapping) {
                cacheHits++;
              } else {
                yagoQueries++;
              }
            } else {
              yagoQueries++;
            }
    
            // Resolve entity (uses cache automatically)
            const resolved = await yagoResolver.resolveEntity(name, 3);
            if (resolved.length > 0) {
              yagoEntities[name] = resolved;
    
              // Store in database if not exists
              if (!entity) {
                const entityId = await db.insertEntity({
                  name,
                  type: type as EntityType,
                  source_file: path,
                  metadata: { detected_from: 'analysis' },
                });
    
                // Store high-confidence mapping
                if (resolved[0].confidence >= 0.9) {
                  await db.upsertYAGOMapping({
                    entity_id: entityId,
                    yago_uri: resolved[0].uri,
                    yago_type: resolved[0].type,
                    confidence: resolved[0].confidence,
                    facts: { facts: resolved[0].facts },
                  });
                }
              }
            }
          } catch (error) {
            console.error(`Failed to resolve YAGO entity for ${name}:`, error);
          }
        }
    
        result.yago_entities = yagoEntities;
        result.enrichment_metadata!.cache_hits = cacheHits;
        result.enrichment_metadata!.yago_queries = yagoQueries;
    
        // Calculate confidence stats
        const allEntities = Object.values(yagoEntities).flat();
        if (allEntities.length > 0) {
          const autoLinked = allEntities.filter((e) => e.confidence >= 0.9).length;
          const avgConfidence =
            allEntities.reduce((sum, e) => sum + e.confidence, 0) / allEntities.length;
    
          result.confidence_stats = {
            total_entities: allEntities.length,
            auto_linked: autoLinked,
            needs_review: allEntities.length - autoLinked,
            avg_confidence: Math.round(avgConfidence * 100) / 100,
          };
        }
      }
    
      // Schema.org enrichment
      if (include_schema) {
        const schemaType = schemaMapper.detectCodebaseType(analysis_result);
        const properties = schemaMapper.extractProperties(analysis_result);
    
        result.schema_annotation = {
          '@type': schemaType,
          ...properties,
        };
    
        // Generate JSON-LD
        result.json_ld = schemaMapper.generateJSONLD({
          entity_id: 0, // Temporary, will be assigned when stored
          schema_type: schemaType,
          properties,
          context_url: 'https://schema.org',
        });
      }
    
      return result;
    }
  • TypeScript interfaces defining input (EnrichContextArgs) and output (EnrichedContext) schemas for the tool.
    export interface EnrichContextArgs {
      path: string;
      analysis_result?: any;
      enrichment_level?: 'minimal' | 'standard' | 'comprehensive';
      include_yago?: boolean;
      include_schema?: boolean;
      max_entities?: number;
    }
    
    export interface EnrichedContext {
      path: string;
      schema_annotation?: any;
      yago_entities?: {
        [key: string]: YAGOEntity[];
      };
      json_ld?: any;
      confidence_stats?: {
        total_entities: number;
        auto_linked: number;
        needs_review: number;
        avg_confidence: number;
      };
      enrichment_metadata?: {
        level: string;
        timestamp: string;
        cache_hits: number;
        yago_queries: number;
      };
    }
  • Tool dispatch handler in switch statement that invokes the enrichContext function and formats the response for MCP.
    case "enrich_context": {
      const result = await enrichContext(args as any);
      const formatted = formatEnrichedContext(result);
      return {
        content: [
          {
            type: "text",
            text: formatted,
          },
        ],
      };
    }
  • MCP tool registration schema in ListToolsRequestSchema response, defining input schema and description.
    name: "enrich_context",
    description: "Enrich codebase context with knowledge graph data from YAGO 4.5 and Schema.org annotations",
    inputSchema: {
      type: "object",
      properties: {
        path: {
          type: "string",
          description: "Root directory path",
        },
        analysis_result: {
          type: "object",
          description: "Previous analysis result from analyze_codebase (optional)",
        },
        enrichment_level: {
          type: "string",
          enum: ["minimal", "standard", "comprehensive"],
          description: "Level of enrichment (minimal: frameworks+languages, standard: +dependencies, comprehensive: +dev deps+patterns)",
          default: "standard",
        },
        include_yago: {
          type: "boolean",
          description: "Include YAGO knowledge graph entity linking",
          default: true,
        },
        include_schema: {
          type: "boolean",
          description: "Include Schema.org semantic annotations",
          default: true,
        },
        max_entities: {
          type: "number",
          description: "Maximum entities to resolve from YAGO",
          default: 10,
          minimum: 1,
          maximum: 50,
        },
      },
      required: ["path"],
    },
  • Helper function to format the EnrichedContext output into readable markdown text used in the tool response.
    export function formatEnrichedContext(context: EnrichedContext): string {
      const lines: string[] = [];
    
      lines.push(`# Enriched Context: ${context.path}`);
      lines.push('');
    
      // Schema.org annotation
      if (context.schema_annotation) {
        lines.push('## Schema.org Annotation');
        lines.push('```json');
        lines.push(JSON.stringify(context.schema_annotation, null, 2));
        lines.push('```');
        lines.push('');
      }
    
      // YAGO entities
      if (context.yago_entities && Object.keys(context.yago_entities).length > 0) {
        lines.push('## YAGO Knowledge Graph Entities');
        lines.push('');
    
        for (const [name, entities] of Object.entries(context.yago_entities)) {
          lines.push(`### ${name}`);
          for (const entity of entities) {
            lines.push(`- **${entity.label}** (confidence: ${entity.confidence.toFixed(2)})`);
            lines.push(`  - Type: ${entity.type}`);
            lines.push(`  - URI: ${entity.uri}`);
            if (entity.description) {
              lines.push(`  - Description: ${entity.description}`);
            }
            if (entity.facts.length > 0) {
              lines.push(`  - Facts: ${entity.facts.length} relationships`);
            }
          }
          lines.push('');
        }
      }
    
      // Confidence stats
      if (context.confidence_stats) {
        lines.push('## Confidence Statistics');
        lines.push(`- Total entities: ${context.confidence_stats.total_entities}`);
        lines.push(`- Auto-linked (≥0.9): ${context.confidence_stats.auto_linked}`);
        lines.push(`- Needs review (<0.9): ${context.confidence_stats.needs_review}`);
        lines.push(`- Average confidence: ${context.confidence_stats.avg_confidence}`);
        lines.push('');
      }
    
      // Enrichment metadata
      if (context.enrichment_metadata) {
        lines.push('## Enrichment Metadata');
        lines.push(`- Level: ${context.enrichment_metadata.level}`);
        lines.push(`- Timestamp: ${context.enrichment_metadata.timestamp}`);
        lines.push(`- Cache hits: ${context.enrichment_metadata.cache_hits}`);
        lines.push(`- YAGO queries: ${context.enrichment_metadata.yago_queries}`);
        lines.push('');
      }
    
      // JSON-LD
      if (context.json_ld) {
        lines.push('## JSON-LD Structured Data');
        lines.push('```json');
        lines.push(JSON.stringify(context.json_ld, null, 2));
        lines.push('```');
      }
    
      return lines.join('\n');
    }
Behavior2/5

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

With no annotations provided, the description carries full burden but only states what the tool does, not how it behaves. It doesn't disclose whether this is a read-only operation, if it modifies files, performance characteristics, error handling, or output format. For a tool with 6 parameters and complex data sources, this lack of behavioral detail 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.

Conciseness5/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 without unnecessary words. Every element ('enrich codebase context', 'knowledge graph data', 'YAGO 4.5', 'Schema.org annotations') earns its place by contributing essential information about what the tool does.

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?

For a tool with 6 parameters, no annotations, no output schema, and complex functionality involving external knowledge graphs, the description is incomplete. It doesn't explain what 'enriched context' means in practice, how results are structured, or what the agent should expect after invocation, leaving significant gaps for effective tool use.

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?

The description mentions YAGO and Schema.org, which map to the 'include_yago' and 'include_schema' parameters, but doesn't add meaningful semantics beyond what's already in the schema (which has 100% coverage). It doesn't explain why one would choose different enrichment levels or how parameters interact, so it provides minimal value over the well-documented schema.

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 ('enrich') and target ('codebase context') with specific data sources ('knowledge graph data from YAGO 4.5 and Schema.org annotations'), making the purpose immediately understandable. However, it doesn't explicitly differentiate from sibling tools like 'generate_context' or 'update_context', which might have overlapping functionality.

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 'analyze_codebase' or 'generate_context'. It mentions optional parameters ('analysis_result' from 'analyze_codebase') but doesn't explain the relationship or when one should be preferred over the other, leaving usage context unclear.

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