How to Use Wiki and CodeGraph Asset Tools with /v3/tools/list and /v3/tools/call APIs

The TencentDB-Agent-Memory service exposes Wiki and CodeGraph knowledge assets through a two-step HTTP pattern where agents first call POST /v3/tools/list to discover available tools, then call POST /v3/tools/call to execute specific operations with structured parameters.

The Memory Knowledge Service in the TencentDB-Agent-Memory repository provides LLM agents with read-only access to structured Wiki content and code repository graphs. Rather than loading entire knowledge bases into prompts, agents use the /v3/tools/list and /v3/tools/call endpoints to dynamically discover and invoke query operations, enabling efficient retrieval of specific pages or code symbols on demand.

The Two-Step Discovery Pattern

The architecture implements a self-discovery mechanism that separates tool enumeration from execution. This pattern ensures agents only interact with whitelisted, read-only operations while maintaining a consistent API contract across both Wiki and CodeGraph asset types.

Step 1 – Discover Tools with /v3/tools/list

Agents initiate the workflow by sending a POST request to the /v3/tools/list endpoint to retrieve the tool schema for a specific knowledge asset. The request requires a valid knowledge_id and the x-tdai-service-id header for authentication.

In src/routes/tools.ts, the createToolsRoutes() function handles this request by validating the ID format using helpers from src/store/ids.ts (isValidIdSegment, isWikiId, and isCodeGraphId). The endpoint returns a JSON envelope containing the resource type (wiki or code-graph), asset metadata, and an array of available tool definitions with their parameters.

curl -X POST https://<memory-knowledge-host>/v3/tools/list \
  -H "Content-Type: application/json" \
  -H "x-tdai-service-id: <service-id>" \
  -d '{"knowledge_id":"wiki-12345678"}'

The response includes the tool whitelist defined in WIKI_TOOLS or CODE_GRAPH_TOOLS, specifying each tool's name, description, and params schema.

Step 2 – Execute Tools with /v3/tools/call

After selecting a tool from the discovery response, agents invoke POST /v3/tools/call with the knowledge_id, tool_name, and params object. The route dispatcher in src/routes/tools.ts routes the request to either the Wiki service (wikiService) or the CodeGraph engine (executeCodeTool) based on the asset type.

curl -X POST https://<memory-knowledge-host>/v3/tools/call \
  -H "Content-Type: application/json" \
  -H "x-tdai-service-id: <service-id>" \
  -d '{
        "knowledge_id":"wiki-12345678",
        "tool_name":"search",
        "params":{"query":"authentication flow","limit":5}
      }'

Both endpoints are defined without the /v3 prefix in their route handlers; the prefix is applied globally when the service mounts the routes in MemoryKnowledge/src/server.ts.

Wiki Asset Tools Implementation

Wiki assets expose query tools for searching and retrieving documentation pages. These tools are strictly read-only, omitting management operations like create, delete, or sync.

Discovering Wiki Tools

When the knowledge_id passes validation as a Wiki ID, the list endpoint returns tools such as search for BM25 full-text search and read_page for fetching specific page content. The validation logic in src/store/ids.ts ensures the ID conforms to the Wiki format before returning the WIKI_TOOLS definitions.

{
  "code": 0,
  "message": "ok",
  "data": {
    "knowledge_id": "wiki-12345678",
    "type": "wiki",
    "name": "Team Wiki",
    "status": "ready",
    "tools": [
      {
        "name": "search",
        "description": "BM25 全文搜索 wiki 页面内容",
        "params": {
          "query": {"type": "string", "required": true}
        }
      },
      {
        "name": "read_page",
        "description": "读取指定页面完整内容",
        "params": {
          "refs": {"type": "array", "required": true}
        }
      }
    ]
  }
}

Calling Wiki Search and Read Operations

The Wiki service implementation in src/routes/wiki.ts processes tool calls and returns structured data directly in the response envelope. Search results include page IDs, titles, and snippets, while read operations return the full page content.

curl -X POST https://<memory-knowledge-host>/v3/tools/call \
  -H "Content-Type: application/json" \
  -H "x-tdai-service-id: <service-id>" \
  -d '{
        "knowledge_id": "wiki-12345678",
        "tool_name": "read_page",
        "params": {"refs": ["page-42"]}
      }'

Wiki tool responses populate the data field with the query results, using HTTP status 200 and code: 0 to indicate success.

CodeGraph Asset Tools Implementation

CodeGraph assets provide tools for code exploration and static analysis, enabling agents to query symbol relationships and retrieve source files without parsing entire repositories.

Discovering CodeGraph Tools

For CodeGraph assets, the discovery endpoint returns tools defined in CODE_GRAPH_TOOL_NAMES, including explore for retrieving complete source code and callers for finding functions that invoke a specific symbol. The ID validation in src/store/ids.ts distinguishes CodeGraph assets using isCodeGraphId.

{
  "code": 0,
  "message": "ok",
  "data": {
    "knowledge_id": "cg-abcdef12",
    "type": "code-graph",
    "name": "Auth Service Repository",
    "status": "ready",
    "tools": [
      {
        "name": "explore",
        "description": "一次调用返回完整源码",
        "params": {
          "query": {"type": "string", "required": true},
          "maxFiles": {"type": "integer"}
        }
      },
      {
        "name": "callers",
        "description": "列出调用 <symbol> 的函数",
        "params": {
          "symbol": {"type": "string", "required": true}
        }
      }
    ]
  }
}

Calling CodeGraph Explore and Analysis Tools

The CodeGraph engine in src/routes/code-graph.ts executes tools against the indexed repository graph. The explore tool accepts a query string and optional maxFiles limit, returning file paths and content.

curl -X POST https://<memory-knowledge-host>/v3/tools/call \
  -H "Content-Type: application/json" \
  -H "x-tdai-service-id: <service-id>" \
  -d '{
        "knowledge_id": "cg-abcdef12",
        "tool_name": "explore",
        "params": {"query": "AuthService loginUser", "maxFiles": 3}
      }'

Error Handling in CodeGraph Responses

Unlike Wiki tools, CodeGraph tools may return execution-level failures within a successful HTTP response. When a tool fails (e.g., symbol not found), the response maintains code: 0 but includes isError: true in the data payload.

{
  "code": 0,
  "message": "ok",
  "data": {
    "text": "symbol not found",
    "isError": true
  }
}

This error contract, documented in MemoryKnowledge/v3-api-memoryknowledge-doc.md, requires callers to inspect the data.isError field to distinguish between successful empty results and execution failures.

Programmatic Integration

Implement the two-step pattern in application code using standard HTTP clients. The following Node.js example uses fetch to wrap the list and call operations:

import fetch from 'node-fetch';

async function listTools(host, serviceId, knowledgeId) {
  const resp = await fetch(`${host}/v3/tools/list`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'x-tdai-service-id': serviceId,
    },
    body: JSON.stringify({ knowledge_id: knowledgeId }),
  });
  return resp.json();
}

async function callTool(host, serviceId, knowledgeId, toolName, params) {
  const resp = await fetch(`${host}/v3/tools/call`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'x-tdai-service-id': serviceId,
    },
    body: JSON.stringify({ 
      knowledge_id: knowledgeId, 
      tool_name: toolName, 
      params 
    }),
  });
  return resp.json();
}

// Usage example
const tools = await listTools('https://api.example.com', 'svc-123', 'wiki-12345678');
const result = await callTool('https://api.example.com', 'svc-123', 'wiki-12345678', 'search', {
  query: 'deployment guide',
  limit: 10
});

Architecture and Source Code

The tool discovery and execution flow is implemented across the following key files in the TencentDB-Agent-Memory repository:

Component Path
Tools route definitions and whitelist MemoryKnowledge/src/routes/tools.ts
Wiki service implementation MemoryKnowledge/src/routes/wiki.ts
CodeGraph service implementation MemoryKnowledge/src/routes/code-graph.ts
ID validation (isWikiId, isCodeGraphId) MemoryKnowledge/src/store/ids.ts
API response utilities (wrapOk, wrapError) MemoryKnowledge/src/api-helpers.ts
Server mount configuration (applies /v3 prefix) MemoryKnowledge/src/server.ts
API contract documentation MemoryKnowledge/v3-api-memoryknowledge-doc.md

Summary

  • Two-step pattern: Agents first call /v3/tools/list to discover available Wiki or CodeGraph tools, then call /v3/tools/call to execute specific operations with validated parameters.
  • Read-only access: Both asset types expose only query tools; management operations are deliberately excluded from the whitelist in src/routes/tools.ts.
  • Type validation: The service validates knowledge_id formats using isWikiId and isCodeGraphId in src/store/ids.ts before returning tool definitions.
  • Error contracts: Wiki tools return results directly in the data field, while CodeGraph tools use the isError flag within data to signal execution failures without changing the HTTP status code.

Frequently Asked Questions

What is the difference between Wiki and CodeGraph tools in the Memory Knowledge Service?

Wiki tools provide full-text search and page retrieval for documentation assets, returning structured content like page titles and snippets. CodeGraph tools offer code-specific operations such as symbol exploration and caller analysis, returning source file contents and relationship graphs. Both follow the same /v3/tools/list and /v3/tools/call pattern but use different validation logic and return formats as defined in their respective service files.

How does the service validate knowledge asset IDs?

The service validates IDs using helper functions in src/store/ids.ts. The isValidIdSegment function checks format constraints, while isWikiId and isCodeGraphId determine the asset type. Invalid IDs are rejected before the tool list is generated, ensuring agents only receive tool definitions for existing, properly formatted knowledge resources.

Why do CodeGraph tools return errors with HTTP 200 status codes?

CodeGraph tools follow a specific error contract where execution failures (like missing symbols) return HTTP 200 with code: 0 but set data.isError to true. This design distinguishes transport-level failures (HTTP 500) from application-level tool errors, allowing agents to handle logic errors programmatically while maintaining consistent response envelope parsing.

Can agents modify knowledge assets through these tool endpoints?

No. The tool endpoints are restricted to read-only operations. The WIKI_TOOL_NAMES and CODE_GRAPH_TOOL_NAMES whitelists in src/routes/tools.ts explicitly exclude management operations such as create, delete, ingest, or sync. Agents can only query existing knowledge through the available search, read, and analysis tools.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →