Saltar a contenido

Estado de fase (MASTER-00): GATE_0 permanece aprobado para el transporte STDIO; el perfil operativo de Nivel 4 añade el transporte remoto Streamable HTTP /mcp y compatibilidad /sse para los ocho tools. Gobernanza: MASTER-00.

Nota de arquitectura (DEC-013): la resolución y validación siguen viviendo en :docugraph-core; STDIO es el transporte local y el perfil HTTP remoto se despliega detrás de Caddy en Oracle. El visor web es de solo lectura y no comparte credenciales MCP.

Kotlin MCP Server Protocol Specification (:docugraph-mcp)

1. Overview & Architecture

The DocuGraph Model Context Protocol (MCP) Server (:docugraph-mcp) is built using the official Kotlin MCP SDK (io.modelcontextprotocol.sdk). It acts as a standard bridge between AI coding agents (Claude Code, Cursor CLI, Junie, Windsurf) and the DocuGraph documentation graph engine.

+-------------------------------------------------------------------+
|                     AI Coding Agent Client                        |
|             (Claude Code, Cursor CLI, Junie, Windsurf)             |
+---------------------------------+---------------------------------+
                                  |
               +------------------+------------------+
               | JSON-RPC 2.0 (MCP Protocol v1.0)   |
               v                                     v
   +-----------------------+             +-----------------------+
   |    Stdio Transport    |             | Streamable HTTP / SSE |
   |   (Local CLI / IDE)   |             |     (/mcp, /sse)      |
   +-----------+-----------+             +-----------+-----------+
               |                                     |
               +------------------+------------------+
                                  |
                                  v
+-------------------------------------------------------------------+
|               Kotlin MCP Server Engine (:docugraph-mcp)           |
|                                                                   |
|   +-------------------+ +-------------------+ +-----------------+ |
|   |  Resources Handler| |   Tools Handler   | | Prompts Handler | |
|   +---------+---------+ +---------+---------+ +--------+--------+ |
+-------------|---------------------|----------------------|--------+
              |                     |                      |
              v                     v                      v
+-------------------------------------------------------------------+
|             Backend Service Engine (:docugraph-backend)           |
|                (BE-03, BE-04, BE-05 Graph Algorithms)             |
+-------------------------------------------------------------------+

2. Server Transport Mechanisms

2.1 Stdio Transport (Standard I/O)

  • Use Case: Local execution when spawned as a child process by desktop IDEs or CLI tools.
  • Protocol Class: StdioServerTransport
  • Invocation: java -jar docugraph-mcp.jar --transport=stdio

2.2 Remote HTTP transports

  • Use Case: Remote client connections through the Oracle deployment.
  • Primary endpoint: /mcp using Streamable HTTP JSON-RPC; clients must preserve the Mcp-Session-Id returned by initialization.
  • Compatibility endpoint: /sse for clients that still require Server-Sent Events.
  • Public boundary: Caddy terminates HTTPS, checks X-MCP-API-KEY, and returns 401 before Ktor for absent or incorrect credentials. Ktor repeats the same exact, fail-closed comparison for direct or internal requests. The internal Ktor port 8080 is never published by Compose.
  • Proxy streaming: Caddy uses streaming-safe reverse proxy settings; the viewer and Gitea have separate hosts and cannot invoke MCP tools.

3. Resources Specification (docugraph:// URI Scheme)

The MCP server exposes workspace documentation artifacts through the standardized docugraph:// URI scheme:

| URI Scheme Pattern | Resource Name | Description | MIME Type | Handler Method | |--------------------|---------------+-------------|-----------|----------------| | docugraph://workspace/nodes | All Workspace Nodes | Returns JSON array of all parsed documentation nodes | application/json | listNodesResource() | | docugraph://workspace/graph | Full Workspace Graph | Returns full JSON adjacency structure (nodes & edges) | application/json | getGraphResource() | | docugraph://workspace/node/{id} | Atomic Node Detail | Returns raw Markdown text and YAML frontmatter of node {id} | text/markdown | getNodeDetailResource(id) | | docugraph://workspace/audit-report | Latest Audit Report | Returns current graph integrity and traceability audit report | application/json | getAuditReportResource() |


4. Executable Tools Specification

The MCP server registers 8 executable tools that AI agents can discover and invoke dynamically:

4.1 Tool 1: get_task_context

  • Description: Performs reverse topological graph traversal starting from taskId, gathering Markdown contents of the target task and its upstream dependencies.
  • Parameters:
  • taskId (String, required): The atomic task identifier (e.g. US-01 or BE-04).
  • maxDepth (Int, optional, default: 5): Maximum traversal depth up the dependency tree.
  • Entitlement Rule: If user subscription is Free tier, effectiveMaxDepth is capped at 2 and truncated = true.
  • Backend Invocation: Delegates to BE-04 getTaskContext.

4.2 Tool 2: get_dependency_graph

  • Description: Returns the directed adjacency graph (nodes and edges) of upstream dependencies (depends_on) and downstream dependents (depended_by) reachable from nodeId, bounded to depth hops in each direction. Canonical signature per DEC-008 (research/99_DECISION_LOG.md).
  • Parameters:
  • nodeId (String, required): The atomic node identifier (e.g. BE-04).
  • depth (Int, optional, default: 3): Maximum traversal depth in each direction.
  • Behavior: If nodeId does not exist, returns NODE_NOT_FOUND error (isError = true).
  • Backend Invocation: Delegates to BE-03 buildGraph (workspace-wide graph source).

4.3 Tool 3: validate_traceability

  • Description: Audits workspace graph integrity, executes Tarjan's SCC algorithm for cycle detection, verifies relative links, and returns a normalized Health Score.
  • Parameters:
  • workspacePath (String, optional): Workspace directory path.
  • Backend Invocation: Delegates to BE-05 validateTraceability.

4.4 Tool 4: list_tasks

  • Description: Lists task nodes with their ID, document path, type, and status, optionally filtered by type and status.
  • Parameters:
  • type (String, optional): Filters tasks by document type.
  • status (String, optional): Filters tasks by task status.
  • Backend Invocation: Reads task status metadata from the in-process workspace graph.

4.5 Tool 5: get_acceptance_criteria

  • Description: Extracts the ordered acceptance criteria declared in a task's Markdown body as structured JSON.
  • Parameters:
  • taskId (String, required): The atomic task identifier whose criteria should be verified.
  • Return: A JSON array of entries with id, text, sourcePath, and section; an absent section returns an empty array.
  • Error: An unknown taskId returns TASK_NOT_FOUND with isError = true.

4.6 Tool 6: analyze_impact

  • Description: Returns the downstream transitive dependents of a task, the longest critical paths, and a bounded impact summary for change safety decisions.
  • Parameters:
  • taskId (String, required): The atomic task identifier whose downstream impact is analyzed.
  • depth (Int, optional, default: 5): Maximum downstream traversal depth.
  • Return: Pretty-printed JSON with affectedNodes, criticalPaths, totalAffected, and truncated.
  • Error: An unknown taskId returns TASK_NOT_FOUND with isError = true.
// Kotlin MCP Tool Declaration Example
val getTaskContextTool = Tool(
    name = "get_task_context",
    description = "Extracts upstream dependency markdown context for a given task ID",
    inputSchema = ToolInputSchema(
        type = "object",
        properties = mapOf(
            "taskId" to PropertySchema(type = "string", description = "Target atomic task ID"),
            "maxDepth" to PropertySchema(type = "integer", description = "Max traversal depth", default = 5)
        ),
        required = listOf("taskId")
    )
)

5. Pre-Engineered Prompts Specification

The MCP server exposes 2 system prompt templates to automate AI coding agent workflows:

5.1 Prompt 1: prompt_implement_task

  • Parameters: taskId: String (required)
  • Behavior: Retrieves context bundle via get_task_context(taskId), formats a system prompt instructing the AI agent to follow DocuGraph integrity mandates, check frontmatter standards, and write minimal code changes.

5.2 Prompt 2: prompt_audit_traceability

  • Parameters: workspacePath: String (optional)
  • Behavior: Retrieves audit report via validate_traceability(), formats prompt instructing AI agent to analyze broken links or cycle paths and generate patch proposals.

6. Authentication & security profiles

6.1 Local STDIO

The local STDIO transport does not add HTTP authentication. The client starts the process with an explicit DOCUGRAPH_WORKSPACE; operating-system process and file permissions protect the local checkout.

6.2 Remote Oracle profile

  • Clients send X-MCP-API-KEY on every remote request to /mcp or /sse.
  • Caddy compares the header with the secret supplied through the Oracle-only MCP_API_KEY environment variable and denies by default with 401.
  • Compose maps that Oracle value to DOCUGRAPH_MCP_API_KEY inside Ktor; a missing or blank server value leaves Ktor fail-closed, and a request is accepted only when the header value matches exactly.
  • The secret is never stored in opencode.json, .agents/mcp_config.json, the repository, the MkDocs site, or the Gitea repository. Local clients use DOCUGRAPH_MCP_API_KEY; OpenCode uses {env:DOCUGRAPH_MCP_API_KEY} and Antigravity uses its local environment placeholder.
  • The remote process has access only to the mounted /workspace checkout; the internal 8080 listener is reachable through the Docker network, not the public firewall.
  • Rotating the key means updating Oracle .env, recreating caddy and docugraph-mcp, updating each local client environment, and repeating the unauthenticated 401 plus authenticated MCP smoke test before reconnecting.

Historical product entitlements and PostgreSQL-backed API-key designs remain catalogued in older documents but are not part of the active self-hosted profile.


7. Verification & Test Plan

  • Protocol Compliance: Run official Model Context Protocol validator against stdio and SSE endpoints.
  • Integration Test: Invoke get_task_context tool with taskId = US-01 via stdio JSON-RPC message, verify formatted markdown response returned in $<150$ms.