Skip to main content
Glama

get_architectural_context

Analyze project architecture to generate architectural decision records, automatically setting up ADR infrastructure when needed for compliance and project success.

Instructions

Get detailed architectural context for specific files or the entire project, automatically sets up ADR infrastructure if missing, and provides outcome-focused workflow for project success

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
filePathNoSpecific file path to analyze (optional, analyzes entire project if not provided)
includeComplianceNoInclude compliance checks in the analysis
conversationContextNoRich context from the calling LLM about user goals and discussion history

Implementation Reference

  • Registration of the 'get_architectural_context' tool in the central TOOL_CATALOG map, including name, descriptions, category, complexity, token estimates, related tools, keywords, requiresAI flag, and simplified inputSchema.
    TOOL_CATALOG.set('get_architectural_context', {
      name: 'get_architectural_context',
      shortDescription: 'Retrieve architectural context and knowledge graph',
      fullDescription:
        'Retrieves the current architectural context including knowledge graph relationships, ADR decisions, and technology mappings.',
      category: 'analysis',
      complexity: 'moderate',
      tokenCost: { min: 2000, max: 5000 },
      hasCEMCPDirective: true, // Phase 4.3: Moderate tool - context assembly
      relatedTools: ['analyze_project_ecosystem', 'discover_existing_adrs'],
      keywords: ['architecture', 'context', 'knowledge', 'graph'],
      requiresAI: false,
      inputSchema: {
        type: 'object',
        properties: {
          includeGraph: { type: 'boolean', default: true },
          includeMetrics: { type: 'boolean', default: false },
        },
      },
    });
  • TypeScript interface defining detailed input arguments for the get_architectural_context tool, used for type safety and validation (projectPath, filePath, analysis options). Note: Simplified schema in catalog.
    export interface GetArchitecturalContextArgs {
      projectPath?: string;
      filePath?: string;
      includeCompliance?: boolean;
      analysisDepth?: string;
      recursiveDepth?: string;
      technologyFocus?: string[];
      analysisScope?: string[];
      includeEnvironment?: boolean;
    }
  • Core logic for generating architectural context data from project ADRs, including ADR discovery, technology/pattern extraction, decision categorization, technology stack building, and recommendations. Likely called by tool handler.
    export async function generateArchitecturalContextResource(
      _params: Record<string, string>,
      searchParams: URLSearchParams,
      kgManager?: KnowledgeGraphManager
    ): Promise<ResourceGenerationResult> {
      const projectPath = searchParams.get('projectPath') || process.cwd();
      const includeDeprecated = searchParams.get('includeDeprecated') !== 'false';
      const includeProposed = searchParams.get('includeProposed') !== 'false';
      const maxDecisions = parseInt(searchParams.get('maxDecisions') || '50', 10);
    
      const cacheKey = 'architectural-context';
    
      // Check cache
      const cached = await resourceCache.get<ResourceGenerationResult>(cacheKey);
      if (cached) {
        return cached;
      }
    
      try {
        // Discover ADRs to build context
        const { discoverAdrsInDirectory } = await import('../utils/adr-discovery.js');
        const pathModule = await import('path');
    
        const adrDirectory = pathModule.resolve(
          projectPath,
          process.env['ADR_DIRECTORY'] || 'docs/adrs'
        );
    
        const discoveryResult = await discoverAdrsInDirectory(adrDirectory, projectPath, {
          includeContent: true,
          includeTimeline: false,
        });
    
        // Categorize ADRs by status
        const statusCounts = {
          accepted: 0,
          deprecated: 0,
          proposed: 0,
          superseded: 0,
          unknown: 0,
        };
    
        const technologies = new Set<string>();
        const patterns = new Set<string>();
        const decisions: ArchitecturalContextData['decisions'] = [];
    
        for (const adr of discoveryResult.adrs) {
          const status = (adr.status || 'unknown').toLowerCase();
          if (status in statusCounts) {
            statusCounts[status as keyof typeof statusCounts]++;
          } else {
            statusCounts.unknown++;
          }
    
          // Skip deprecated if not requested
          if (!includeDeprecated && status === 'deprecated') continue;
          if (!includeProposed && status === 'proposed') continue;
    
          // Extract technologies from content
          const content = `${adr.context || ''} ${adr.decision || ''} ${adr.consequences || ''}`;
          extractTechnologies(content, technologies);
          extractPatterns(content, patterns);
    
          // Add to decisions list
          if (decisions.length < maxDecisions) {
            decisions.push({
              id: adr.filename.replace(/\.md$/, ''),
              title: adr.title || 'Untitled',
              status: adr.status || 'unknown',
              category: categorizeAdr(adr.title || '', content),
              impact: determineImpact(content),
              dependencies: extractDependencies(content),
            });
          }
        }
    
        // Build technology stack
        const technologyStack = categorizeTechnologies([...technologies]);
    
        // Build patterns list
        const patternsList = [...patterns].map(pattern => ({
          name: pattern,
          description: getPatternDescription(pattern),
          usedIn: findPatternUsage(pattern, discoveryResult.adrs),
          relatedAdrs: findRelatedAdrs(pattern, discoveryResult.adrs),
        }));
    
        // Generate recommendations
        const recommendations = generateRecommendations(discoveryResult.adrs, statusCounts, [
          ...technologies,
        ]);
    
        // Get additional context from knowledge graph if available
        if (kgManager) {
          try {
            const kg = await kgManager.loadKnowledgeGraph();
            if (kg && kg.intents) {
              // Extract technologies and patterns from intent goals
              kg.intents.forEach((intent: any) => {
                if (intent.parsedGoals) {
                  intent.parsedGoals.forEach((goal: string) => {
                    // Simple heuristic to extract tech/pattern mentions
                    const lowerGoal = goal.toLowerCase();
                    if (lowerGoal.includes('technology') || lowerGoal.includes('framework')) {
                      // Could extract specific technologies here
                    }
                  });
                }
              });
            }
          } catch {
            // Knowledge graph not available
          }
        }
    
        const contextData: ArchitecturalContextData = {
          summary: {
            totalAdrs: discoveryResult.totalAdrs,
            activeDecisions: statusCounts.accepted,
            deprecatedDecisions: statusCounts.deprecated,
            proposedDecisions: statusCounts.proposed,
            technologiesUsed: [...technologies].sort(),
            architecturalPatterns: [...patterns].sort(),
          },
          decisions,
          technologyStack,
          patterns: patternsList,
          recommendations,
          timestamp: new Date().toISOString(),
          projectPath,
        };
    
        const result: ResourceGenerationResult = {
          data: contextData,
          contentType: 'application/json',
          lastModified: new Date().toISOString(),
          cacheKey,
          ttl: 300, // 5 minutes cache
          etag: generateETag(contextData),
        };
    
        // Cache result
        resourceCache.set(cacheKey, result, result.ttl);
    
        return result;
      } catch (error) {
        throw new McpAdrError(
          `Failed to generate architectural context: ${error instanceof Error ? error.message : String(error)}`,
          'RESOURCE_GENERATION_ERROR'
        );
      }
    }
  • TOOL_CATALOG entry provides metadata used by tool dispatcher/search_tools for dynamic tool discovery and lightweight listing.
    TOOL_CATALOG.set('get_architectural_context', {
      name: 'get_architectural_context',
      shortDescription: 'Retrieve architectural context and knowledge graph',
      fullDescription:
        'Retrieves the current architectural context including knowledge graph relationships, ADR decisions, and technology mappings.',
      category: 'analysis',
      complexity: 'moderate',
      tokenCost: { min: 2000, max: 5000 },
      hasCEMCPDirective: true, // Phase 4.3: Moderate tool - context assembly
      relatedTools: ['analyze_project_ecosystem', 'discover_existing_adrs'],
      keywords: ['architecture', 'context', 'knowledge', 'graph'],
      requiresAI: false,
      inputSchema: {
        type: 'object',
        properties: {
          includeGraph: { type: 'boolean', default: true },
          includeMetrics: { type: 'boolean', default: false },
        },
      },
    });
  • References 'get_architectural_context' as a related tool in the analyze_project_ecosystem example within tool catalog resource.
    *         relatedTools: ["get_architectural_context"],
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 'automatically sets up ADR infrastructure if missing' and 'provides outcome-focused workflow,' which hints at side effects and workflow integration. However, it lacks details on permissions, rate limits, error handling, or what 'outcome-focused workflow' entails, leaving significant gaps for a tool with potential setup actions.

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

Conciseness3/5

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

The description is a single run-on sentence that combines multiple concepts: getting context, setting up infrastructure, and providing workflow. It's somewhat front-loaded but could be more structured for clarity. While concise, it sacrifices precision by cramming too much into one sentence without clear separation of functions.

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 (3 parameters, nested objects, no annotations, no output schema), the description is incomplete. It fails to explain the return values, error conditions, or the implications of 'automatically sets up ADR infrastructure' (e.g., what happens, permissions needed). For a tool with setup actions and rich input, more behavioral context is needed to guide effective 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?

Schema description coverage is 100%, so the schema already documents all three parameters thoroughly. The description adds no specific parameter semantics beyond implying analysis scope ('specific files or the entire project'), which is already covered in the schema's 'filePath' description. With high schema coverage, the baseline is 3, as the description doesn't enhance parameter understanding.

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 tool's purpose: 'Get detailed architectural context for specific files or the entire project.' It specifies the verb ('Get') and resource ('architectural context') with scope options. However, it doesn't explicitly differentiate from sibling tools like 'analyze_project_ecosystem' or 'get_server_context,' which might offer 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 minimal usage guidance. It mentions analyzing files or the entire project and setting up ADR infrastructure, but offers no explicit when-to-use advice, prerequisites, or alternatives among the many sibling tools. For example, it doesn't clarify when to use this versus 'analyze_project_ecosystem' or 'get_server_context.'

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/tosin2013/mcp-adr-analysis-server'

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