forked from nicobailon/pi-mcp-adapter
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmetadata-cache.ts
More file actions
205 lines (182 loc) · 6.39 KB
/
metadata-cache.ts
File metadata and controls
205 lines (182 loc) · 6.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
// metadata-cache.ts - Persistent MCP metadata cache
import { existsSync, readFileSync, writeFileSync, renameSync, mkdirSync } from "node:fs";
import { homedir } from "node:os";
import { dirname, join, resolve } from "node:path";
import { createHash } from "node:crypto";
import { getToolUiResourceUri } from "@modelcontextprotocol/ext-apps/app-bridge";
import type { McpTool, McpResource, ServerEntry, ToolMetadata } from "./types.js";
import { formatToolName, isToolExcluded } from "./types.js";
import { resourceNameToToolName } from "./resource-tools.js";
import { extractToolUiStreamMode } from "./utils.js";
const CACHE_VERSION = 1;
const CACHE_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000;
const CACHE_PATH = join(homedir(), ".pi", "agent", "mcp-cache.json");
export interface CachedTool {
name: string;
description?: string;
inputSchema?: unknown;
uiResourceUri?: string;
uiStreamMode?: "eager" | "stream-first";
}
export interface CachedResource {
uri: string;
name: string;
description?: string;
}
export interface ServerCacheEntry {
configHash: string;
tools: CachedTool[];
resources: CachedResource[];
cachedAt: number;
}
export interface MetadataCache {
version: number;
servers: Record<string, ServerCacheEntry>;
}
export function getMetadataCachePath(): string {
if (process.env.PI_CODING_AGENT_DIR) {
return resolve(process.env.PI_CODING_AGENT_DIR, "mcp-cache.json");
}
return CACHE_PATH;
}
export function loadMetadataCache(): MetadataCache | null {
const cachePath = getMetadataCachePath();
if (!existsSync(cachePath)) return null;
try {
const raw = JSON.parse(readFileSync(cachePath, "utf-8"));
if (!raw || typeof raw !== "object") return null;
if (raw.version !== CACHE_VERSION) return null;
if (!raw.servers || typeof raw.servers !== "object") return null;
return raw as MetadataCache;
} catch {
return null;
}
}
export function saveMetadataCache(cache: MetadataCache): void {
const cachePath = getMetadataCachePath();
const dir = dirname(cachePath);
mkdirSync(dir, { recursive: true });
let merged: MetadataCache = { version: CACHE_VERSION, servers: {} };
try {
if (existsSync(cachePath)) {
const existing = JSON.parse(readFileSync(cachePath, "utf-8")) as MetadataCache;
if (existing && existing.version === CACHE_VERSION && existing.servers) {
merged.servers = { ...existing.servers };
}
}
} catch {
// Ignore parse errors and proceed with empty cache
}
merged.version = CACHE_VERSION;
merged.servers = { ...merged.servers, ...cache.servers };
const tmpPath = `${cachePath}.${process.pid}.tmp`;
writeFileSync(tmpPath, JSON.stringify(merged, null, 2), "utf-8");
renameSync(tmpPath, cachePath);
}
export function computeServerHash(definition: ServerEntry): string {
// Hash only fields that affect server identity and tool/resource output.
// Exclude lifecycle, idleTimeout, debug — those are runtime behavior settings
// that don't change which tools a server exposes.
const identity: Record<string, unknown> = {
command: definition.command,
args: definition.args,
env: definition.env,
cwd: definition.cwd,
url: definition.url,
headers: definition.headers,
auth: definition.auth,
bearerToken: definition.bearerToken,
bearerTokenEnv: definition.bearerTokenEnv,
exposeResources: definition.exposeResources,
excludeTools: definition.excludeTools,
};
const normalized = stableStringify(identity);
return createHash("sha256").update(normalized).digest("hex");
}
export function isServerCacheValid(
entry: ServerCacheEntry,
definition: ServerEntry,
maxAgeMs: number = CACHE_MAX_AGE_MS
): boolean {
if (!entry || entry.configHash !== computeServerHash(definition)) return false;
if (!entry.cachedAt || typeof entry.cachedAt !== "number") return false;
if (maxAgeMs > 0 && Date.now() - entry.cachedAt > maxAgeMs) return false;
return true;
}
export function reconstructToolMetadata(
serverName: string,
entry: ServerCacheEntry,
prefix: "server" | "none" | "short",
definition: Pick<ServerEntry, "exposeResources" | "excludeTools">
): ToolMetadata[] {
const metadata: ToolMetadata[] = [];
for (const tool of entry.tools ?? []) {
if (!tool?.name) continue;
if (isToolExcluded(tool.name, serverName, prefix, definition.excludeTools)) {
continue;
}
metadata.push({
name: formatToolName(tool.name, serverName, prefix),
originalName: tool.name,
description: tool.description ?? "",
inputSchema: tool.inputSchema,
uiResourceUri: tool.uiResourceUri,
uiStreamMode: tool.uiStreamMode,
});
}
if (definition.exposeResources !== false) {
for (const resource of entry.resources ?? []) {
if (!resource?.name || !resource?.uri) continue;
const baseName = `get_${resourceNameToToolName(resource.name)}`;
if (isToolExcluded(baseName, serverName, prefix, definition.excludeTools)) {
continue;
}
metadata.push({
name: formatToolName(baseName, serverName, prefix),
originalName: baseName,
description: resource.description ?? `Read resource: ${resource.uri}`,
resourceUri: resource.uri,
});
}
}
return metadata;
}
export function serializeTools(tools: McpTool[]): CachedTool[] {
return tools
.filter(t => t?.name)
.map(t => ({
name: t.name,
description: t.description,
inputSchema: t.inputSchema,
uiResourceUri: tryGetToolUiResourceUri(t),
uiStreamMode: extractToolUiStreamMode(t._meta),
}));
}
export function serializeResources(resources: McpResource[]): CachedResource[] {
return resources
.filter(r => r?.name && r?.uri)
.map(r => ({
uri: r.uri,
name: r.name,
description: r.description,
}));
}
function stableStringify(value: unknown): string {
if (value === null || value === undefined || typeof value !== "object") {
const serialized = JSON.stringify(value);
return serialized === undefined ? "undefined" : serialized;
}
if (Array.isArray(value)) {
return `[${value.map(v => stableStringify(v)).join(",")}]`;
}
const obj = value as Record<string, unknown>;
const keys = Object.keys(obj).sort();
return `{${keys.map(k => `${JSON.stringify(k)}:${stableStringify(obj[k])}`).join(",")}}`;
}
function tryGetToolUiResourceUri(tool: McpTool): string | undefined {
try {
return getToolUiResourceUri({ _meta: tool._meta });
} catch {
return undefined;
}
}