Here is everything you asked for, organized by component.
1. MCP Tool: record_agent_intent Implementation
File: /Users/hobo/Projects/AgentLog/packages/backend/src/mcp.ts
This is the complete MCP server. The record_agent_intent tool definition and its database write are both in this single file.
Tool Definition (input schema)
{
name: "record_agent_intent",
description: "记录 AI 重构或编写代码的上下文意图。在完成一项任务后调用此工具,将决策逻辑持久化到本地数据库。",
inputSchema: {
type: "object",
properties: {
task: { type: "string", description: "当前执行的任务或目标(简要概述)" },
reasoning: { type: "string", description: "重构或修改代码的深度决策逻辑和原因(越详细越好)" },
affected_files: { type: "array", items: { type: "string" }, description: "受影响的文件路径列表(相对于工作区根目录)" },
},
required: ["task", "reasoning"], // affected_files is optional
},
}
Database INSERT (the actual write)
const db = getDatabase();
const id = nanoid();
const stmt = db.prepare(`
INSERT INTO agent_sessions (
id, provider, model, source, workspace_path,
prompt, reasoning, response,
affected_files, duration_ms, tags, metadata
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
`);
stmt.run(
id,
"mcp", // provider — hardcoded
"unknown", // model — hardcoded (Agent doesn't report it)
"mcp-tool-call", // source — hardcoded
process.cwd(), // workspace_path — the MCP process's cwd
task, // prompt — maps from the "task" input param
reasoning, // reasoning — maps from the "reasoning" input param
`[MCP] ${task}`, // response — synthetic, prefixed summary
toJson(affectedFiles), // affected_files — JSON array, defaults to []
0, // duration_ms — always 0
toJson([]), // tags — always empty
toJson({}), // metadata — always empty
);
Key observations about the MCP tool's INSERT:
- It does not set
created_at — the column's DDL default (strftime('%Y-%m-%dT%H:%M:%fZ', 'now')) handles that.
- It does not set
commit_hash — left as NULL (unbound).
- It does not set
note — left as NULL.
- The
source value is "mcp-tool-call", which is not in the AgentSource union type defined in @agentlog/shared (that type has "claude-code" | "cline" | "cursor" | "copilot" | "continue" | "direct-api" | "unknown"). Similarly provider: "mcp" is not in the ModelProvider union.
2. POST /api/sessions Route Handler
File: /Users/hobo/Projects/AgentLog/packages/backend/src/routes/sessions.ts (lines 46-111)
Validation
The route requires these fields (400 error if missing):
prompt (string) -- required
response (string) -- required
provider (string) -- required
model (string) -- required
workspacePath (string) -- required
Fields passed to createSession()
const session = createSession({
provider: body.provider as ModelProvider,
model: body.model,
source: (body.source as AgentSource) ?? 'unknown', // defaults to 'unknown'
workspacePath: body.workspacePath,
prompt: body.prompt,
reasoning: body.reasoning, // optional
response: body.response,
affectedFiles: body.affectedFiles ?? [], // defaults to []
durationMs: body.durationMs ?? 0, // defaults to 0
tags: body.tags ?? [], // defaults to []
note: body.note, // optional
metadata: body.metadata, // optional
});
Returns 201 with { success: true, data: session }.
3. logService.createSession() Function
File: /Users/hobo/Projects/AgentLog/packages/backend/src/services/logService.ts (lines 56-95)
export function createSession(req: CreateSessionRequest): AgentSession {
const db = getDatabase();
const id = nanoid();
const createdAt = new Date().toISOString();
db.prepare(`
INSERT INTO agent_sessions (
id, created_at, provider, model, source, workspace_path,
prompt, reasoning, response, affected_files,
duration_ms, tags, note, metadata
) VALUES (
@id, @created_at, @provider, @model, @source, @workspace_path,
@prompt, @reasoning, @response, @affected_files,
@duration_ms, @tags, @note, @metadata
)
`).run({
id,
created_at: createdAt,
provider: req.provider,
model: req.model,
source: req.source,
workspace_path: req.workspacePath,
prompt: req.prompt,
reasoning: req.reasoning ?? null,
response: req.response,
affected_files: toJson(req.affectedFiles ?? []),
duration_ms: req.durationMs,
tags: toJson(req.tags ?? []),
note: req.note ?? null,
metadata: toJson(req.metadata ?? {}),
});
// Re-reads from DB to ensure return value matches what's stored
const created = getSessionById(id);
if (!created) {
throw new Error(`[logService] 会话写入失败,id=${id}`);
}
return created;
}
Key difference vs MCP tool: logService.createSession sets 14 columns (including created_at and note), uses named parameters (@id, @created_at, etc.), and re-reads the row after insert. The MCP tool sets 12 columns (omitting created_at and note), uses positional ? parameters, and does not re-read.
4. Database Schema / DDL for agent_sessions
File: /Users/hobo/Projects/AgentLog/packages/backend/src/db/database.ts (lines 54-79)
Table DDL
CREATE TABLE IF NOT EXISTS agent_sessions (
id TEXT NOT NULL PRIMARY KEY,
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now')),
provider TEXT NOT NULL,
model TEXT NOT NULL,
source TEXT NOT NULL DEFAULT 'unknown',
workspace_path TEXT NOT NULL,
prompt TEXT NOT NULL,
reasoning TEXT,
response TEXT NOT NULL,
commit_hash TEXT,
affected_files TEXT NOT NULL DEFAULT '[]',
duration_ms INTEGER NOT NULL DEFAULT 0,
tags TEXT NOT NULL DEFAULT '[]',
note TEXT,
metadata TEXT NOT NULL DEFAULT '{}'
);
Indexes
CREATE INDEX IF NOT EXISTS idx_sessions_created_at ON agent_sessions (created_at);
CREATE INDEX IF NOT EXISTS idx_sessions_workspace ON agent_sessions (workspace_path);
CREATE INDEX IF NOT EXISTS idx_sessions_provider ON agent_sessions (provider);
CREATE INDEX IF NOT EXISTS idx_sessions_commit_hash ON agent_sessions (commit_hash);
SessionRow TypeScript type (the raw DB row shape)
export type SessionRow = {
id: string;
created_at: string;
provider: string;
model: string;
source: string;
workspace_path: string;
prompt: string;
reasoning: string | null;
response: string;
commit_hash: string | null;
affected_files: string; // JSON array string
duration_ms: number;
tags: string; // JSON array string
note: string | null;
metadata: string; // JSON object string
};
CreateSessionRequest (shared type)
export interface CreateSessionRequest {
provider: ModelProvider;
model: string;
source: AgentSource;
workspacePath: string;
prompt: string;
reasoning?: string;
response: string;
affectedFiles?: string[];
durationMs: number;
tags?: string[];
note?: string;
metadata?: Record<string, unknown>;
}
Migration system
The schema is at version 1. Migrations are tracked in a schema_version table and run transactionally at database startup (getDatabase() calls runMigrations()). The version 1 migration creates both agent_sessions and commit_bindings tables with their indexes.
Summary: Column-by-column comparison of the two write paths
| Column | logService.createSession (HTTP API) | MCP record_agent_intent |
|---|
id | nanoid() | nanoid() |
created_at | new Date().toISOString() (explicit) | DDL default (SQLite strftime) |
provider | from request body | hardcoded "mcp" |
model | from request body | hardcoded "unknown" |
source | from request body | hardcoded "mcp-tool-call" |
workspace_path | from request body | process.cwd() |
prompt | from request body | task parameter |
reasoning | from request body (nullable) | reasoning parameter |
response | from request body | "[MCP] ${task}" (synthetic) |
commit_hash | not set (NULL) | not set (NULL) |
affected_files | JSON from request body (default []) | JSON from affected_files param (default []) |
duration_ms | from request body (default 0) | hardcoded 0 |
tags | JSON from request body (default []) | hardcoded [] |
note | from request body (nullable) | not set (NULL via DDL) |
metadata | JSON from request body (default {}) | hardcoded {} |