File size: 15,281 Bytes
2517be1 | 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 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 | /**
* mcpResourceStore - Reactive State Store for MCP Resources
*
* Manages MCP protocol resources:
* - Resource discovery and listing per server
* - Resource content caching
* - Resource subscriptions
* - Resource attachments for chat context
*
* @see MCP Protocol Specification: https://modelcontextprotocol.io/specification/2025-06-18/server/resources
*/
import { SvelteMap } from 'svelte/reactivity';
import { AttachmentType } from '$lib/enums';
import {
MCP_RESOURCE_ATTACHMENT_ID_PREFIX,
MCP_RESOURCE_CACHE_MAX_ENTRIES,
MCP_RESOURCE_CACHE_TTL_MS,
NEWLINE_SEPARATOR,
RESOURCE_UNKNOWN_TYPE,
BINARY_CONTENT_LABEL
} from '$lib/constants';
import { normalizeResourceUri } from '$lib/utils';
import type {
MCPResource,
MCPResourceTemplate,
MCPResourceContent,
MCPResourceInfo,
MCPResourceTemplateInfo,
MCPCachedResource,
MCPResourceAttachment,
MCPResourceSubscription,
MCPServerResources,
DatabaseMessageExtraMcpResource
} from '$lib/types';
function generateAttachmentId(): string {
return `${MCP_RESOURCE_ATTACHMENT_ID_PREFIX}-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`;
}
class MCPResourceStore {
private _serverResources = $state<SvelteMap<string, MCPServerResources>>(new SvelteMap());
private _cachedResources = $state<SvelteMap<string, MCPCachedResource>>(new SvelteMap());
private _subscriptions = $state<SvelteMap<string, MCPResourceSubscription>>(new SvelteMap());
private _attachments = $state<MCPResourceAttachment[]>([]);
private _isLoading = $state(false);
get serverResources(): Map<string, MCPServerResources> {
return this._serverResources;
}
get cachedResources(): Map<string, MCPCachedResource> {
return this._cachedResources;
}
get subscriptions(): Map<string, MCPResourceSubscription> {
return this._subscriptions;
}
get attachments(): MCPResourceAttachment[] {
return this._attachments;
}
get isLoading(): boolean {
return this._isLoading;
}
get totalResourceCount(): number {
let count = 0;
for (const serverRes of this._serverResources.values()) {
count += serverRes.resources.length;
}
return count;
}
get totalTemplateCount(): number {
let count = 0;
for (const serverRes of this._serverResources.values()) {
count += serverRes.templates.length;
}
return count;
}
get attachmentCount(): number {
return this._attachments.length;
}
get hasAttachments(): boolean {
return this._attachments.length > 0;
}
/**
*
*
* Server Resources Management
*
*
*/
/**
* Set resources for a server (called after listResources)
*/
setServerResources(
serverName: string,
resources: MCPResource[],
templates: MCPResourceTemplate[]
): void {
this._serverResources.set(serverName, {
serverName,
resources,
templates,
lastFetched: new Date(),
loading: false,
error: undefined
});
console.log(
`[MCPResources][${serverName}] Set ${resources.length} resources, ${templates.length} templates`
);
}
/**
* Set loading state for a server's resources
*/
setServerLoading(serverName: string, loading: boolean): void {
const existing = this._serverResources.get(serverName);
if (existing) {
this._serverResources.set(serverName, { ...existing, loading });
} else {
this._serverResources.set(serverName, {
serverName,
resources: [],
templates: [],
loading,
error: undefined
});
}
}
/**
* Set error state for a server's resources
*/
setServerError(serverName: string, error: string): void {
const existing = this._serverResources.get(serverName);
if (existing) {
this._serverResources.set(serverName, { ...existing, loading: false, error });
} else {
this._serverResources.set(serverName, {
serverName,
resources: [],
templates: [],
loading: false,
error
});
}
}
/**
* Get resources for a specific server
*/
getServerResources(serverName: string): MCPServerResources | undefined {
return this._serverResources.get(serverName);
}
/**
* Get all resources as MCPResourceInfo array (flattened with server names)
*/
getAllResourceInfos(): MCPResourceInfo[] {
const result: MCPResourceInfo[] = [];
for (const [serverName, serverRes] of this._serverResources) {
for (const resource of serverRes.resources) {
result.push({
uri: resource.uri,
name: resource.name,
title: resource.title,
description: resource.description,
mimeType: resource.mimeType,
serverName,
annotations: resource.annotations,
icons: resource.icons
});
}
}
return result;
}
/**
* Get all templates as MCPResourceTemplateInfo array (flattened with server names)
*/
getAllTemplateInfos(): MCPResourceTemplateInfo[] {
const result: MCPResourceTemplateInfo[] = [];
for (const [serverName, serverRes] of this._serverResources) {
for (const template of serverRes.templates) {
result.push({
uriTemplate: template.uriTemplate,
name: template.name,
title: template.title,
description: template.description,
mimeType: template.mimeType,
serverName,
annotations: template.annotations,
icons: template.icons
});
}
}
return result;
}
/**
* Clear resources for a server (e.g., when disconnected)
*/
clearServerResources(serverName: string): void {
this._serverResources.delete(serverName);
// Also clear cached content for this server's resources
for (const [uri, cached] of this._cachedResources) {
if (cached.resource.serverName === serverName) {
this._cachedResources.delete(uri);
}
}
// Clear subscriptions for this server
for (const [uri, sub] of this._subscriptions) {
if (sub.serverName === serverName) {
this._subscriptions.delete(uri);
}
}
console.log(`[MCPResources][${serverName}] Cleared all resources`);
}
/**
*
*
* Resource Content Caching
*
*
*/
/**
* Cache resource content after reading
*/
cacheResourceContent(resource: MCPResourceInfo, content: MCPResourceContent[]): void {
// Enforce cache size limit
if (this._cachedResources.size >= MCP_RESOURCE_CACHE_MAX_ENTRIES) {
// Remove oldest entry
const oldestKey = this._cachedResources.keys().next().value;
if (oldestKey) {
this._cachedResources.delete(oldestKey);
}
}
this._cachedResources.set(resource.uri, {
resource,
content,
fetchedAt: new Date(),
subscribed: this._subscriptions.has(resource.uri)
});
console.log(`[MCPResources] Cached content for: ${resource.uri}`);
}
/**
* Get cached content for a resource
*/
getCachedContent(uri: string): MCPCachedResource | undefined {
const cached = this._cachedResources.get(uri);
if (!cached) return undefined;
// Check if cache is still valid
const age = Date.now() - cached.fetchedAt.getTime();
if (age > MCP_RESOURCE_CACHE_TTL_MS && !cached.subscribed) {
// Cache expired and not subscribed, remove it
this._cachedResources.delete(uri);
return undefined;
}
return cached;
}
/**
* Invalidate cached content for a resource (e.g., on update notification)
*/
invalidateCache(uri: string): void {
this._cachedResources.delete(uri);
console.log(`[MCPResources] Invalidated cache for: ${uri}`);
}
/**
* Clear all cached content
*/
clearCache(): void {
this._cachedResources.clear();
console.log(`[MCPResources] Cleared all cached content`);
}
/**
*
*
* Subscriptions
*
*
*/
/**
* Register a subscription for a resource
*/
addSubscription(uri: string, serverName: string): void {
this._subscriptions.set(uri, {
uri,
serverName,
subscribedAt: new Date()
});
// Update cached resource if exists
const cached = this._cachedResources.get(uri);
if (cached) {
this._cachedResources.set(uri, { ...cached, subscribed: true });
}
console.log(`[MCPResources] Added subscription: ${uri}`);
}
/**
* Remove a subscription for a resource
*/
removeSubscription(uri: string): void {
this._subscriptions.delete(uri);
// Update cached resource if exists
const cached = this._cachedResources.get(uri);
if (cached) {
this._cachedResources.set(uri, { ...cached, subscribed: false });
}
console.log(`[MCPResources] Removed subscription: ${uri}`);
}
/**
* Check if a resource is subscribed
*/
isSubscribed(uri: string): boolean {
return this._subscriptions.has(uri);
}
/**
* Handle resource update notification
*/
handleResourceUpdate(uri: string): void {
// Invalidate cache so next read gets fresh content
this.invalidateCache(uri);
// Update subscription last update time
const sub = this._subscriptions.get(uri);
if (sub) {
this._subscriptions.set(uri, { ...sub, lastUpdate: new Date() });
}
console.log(`[MCPResources] Resource updated: ${uri}`);
}
/**
* Handle resources list changed notification
*/
handleResourcesListChanged(serverName: string): void {
// Mark server resources as needing refresh
const existing = this._serverResources.get(serverName);
if (existing) {
this._serverResources.set(serverName, {
...existing,
lastFetched: undefined // Mark as stale
});
}
console.log(`[MCPResources][${serverName}] Resources list changed, needs refresh`);
}
/**
*
*
* Attachments (for chat context)
*
*
*/
/**
* Add a resource attachment to the current chat context
*/
addAttachment(resource: MCPResourceInfo): MCPResourceAttachment {
const attachment: MCPResourceAttachment = {
id: generateAttachmentId(),
resource,
loading: true
};
this._attachments = [...this._attachments, attachment];
console.log(`[MCPResources] Added attachment: ${resource.uri}`);
return attachment;
}
/**
* Update attachment with fetched content
*/
updateAttachmentContent(attachmentId: string, content: MCPResourceContent[]): void {
this._attachments = this._attachments.map((att) =>
att.id === attachmentId ? { ...att, content, loading: false, error: undefined } : att
);
}
/**
* Update attachment with error
*/
updateAttachmentError(attachmentId: string, error: string): void {
this._attachments = this._attachments.map((att) =>
att.id === attachmentId ? { ...att, loading: false, error } : att
);
}
/**
* Remove an attachment
*/
removeAttachment(attachmentId: string): void {
this._attachments = this._attachments.filter((att) => att.id !== attachmentId);
console.log(`[MCPResources] Removed attachment: ${attachmentId}`);
}
/**
* Clear all attachments
*/
clearAttachments(): void {
this._attachments = [];
console.log(`[MCPResources] Cleared all attachments`);
}
/**
* Get attachment by ID
*/
getAttachment(attachmentId: string): MCPResourceAttachment | undefined {
return this._attachments.find((att) => att.id === attachmentId);
}
/**
* Check if a resource is already attached
*/
isAttached(uri: string): boolean {
const normalizedUri = normalizeResourceUri(uri);
return this._attachments.some(
(att) => att.resource.uri === uri || normalizeResourceUri(att.resource.uri) === normalizedUri
);
}
/**
*
*
* Utility Methods
*
*
*/
/**
* Set global loading state
*/
setLoading(loading: boolean): void {
this._isLoading = loading;
}
/**
* Find resource info by URI across all servers
*/
findResourceByUri(uri: string): MCPResourceInfo | undefined {
const normalizedUri = normalizeResourceUri(uri);
for (const [serverName, serverRes] of this._serverResources) {
const resource =
serverRes.resources.find((r) => r.uri === uri) ??
serverRes.resources.find((r) => normalizeResourceUri(r.uri) === normalizedUri);
if (resource) {
return {
uri: resource.uri,
name: resource.name,
title: resource.title,
description: resource.description,
mimeType: resource.mimeType,
serverName,
annotations: resource.annotations,
icons: resource.icons
};
}
}
return undefined;
}
/**
* Find server name for a resource URI
*/
findServerForUri(uri: string): string | undefined {
for (const [serverName, serverRes] of this._serverResources) {
if (serverRes.resources.some((r) => r.uri === uri)) {
return serverName;
}
}
return undefined;
}
/**
* Clear all state (e.g., on full reset)
*/
clear(): void {
this._serverResources.clear();
this._cachedResources.clear();
this._subscriptions.clear();
this._attachments = [];
this._isLoading = false;
console.log(`[MCPResources] Cleared all state`);
}
/**
* Get resource content as text for chat context
* Formats content for inclusion in LLM prompts
*/
formatAttachmentsForContext(): string {
if (this._attachments.length === 0) return '';
const parts: string[] = [];
for (const attachment of this._attachments) {
if (attachment.error) continue;
if (!attachment.content || attachment.content.length === 0) continue;
const resourceName = attachment.resource.title || attachment.resource.name;
const serverName = attachment.resource.serverName;
for (const content of attachment.content) {
if ('text' in content && content.text) {
parts.push(`\n\n--- Resource: ${resourceName} (from ${serverName}) ---\n${content.text}`);
} else if ('blob' in content && content.blob) {
// For binary content, just note it exists
parts.push(
`\n\n--- Resource: ${resourceName} (from ${serverName}) ---\n[${BINARY_CONTENT_LABEL}: ${content.mimeType || RESOURCE_UNKNOWN_TYPE}]`
);
}
}
}
return parts.join('');
}
/**
* Convert current resource attachments to DatabaseMessageExtra[] for persisting with a message.
* Each attachment becomes a DatabaseMessageExtraMcpResource stored on the user message.
*/
toMessageExtras(): DatabaseMessageExtraMcpResource[] {
const extras: DatabaseMessageExtraMcpResource[] = [];
for (const attachment of this._attachments) {
if (attachment.error) continue;
if (!attachment.content || attachment.content.length === 0) continue;
const resourceName = attachment.resource.title || attachment.resource.name;
const contentParts: string[] = [];
for (const content of attachment.content) {
if ('text' in content && content.text) {
contentParts.push(content.text);
} else if ('blob' in content && content.blob) {
contentParts.push(
`[${BINARY_CONTENT_LABEL}: ${content.mimeType || RESOURCE_UNKNOWN_TYPE}]`
);
}
}
if (contentParts.length > 0) {
extras.push({
type: AttachmentType.MCP_RESOURCE,
name: resourceName,
uri: attachment.resource.uri,
serverName: attachment.resource.serverName,
content: contentParts.join(NEWLINE_SEPARATOR),
mimeType: attachment.resource.mimeType
});
}
}
return extras;
}
}
export const mcpResourceStore = new MCPResourceStore();
// Export convenience functions
export const mcpResources = () => mcpResourceStore.serverResources;
export const mcpResourceAttachments = () => mcpResourceStore.attachments;
export const mcpResourceAttachmentCount = () => mcpResourceStore.attachmentCount;
export const mcpHasResourceAttachments = () => mcpResourceStore.hasAttachments;
export const mcpTotalResourceCount = () => mcpResourceStore.totalResourceCount;
export const mcpResourcesLoading = () => mcpResourceStore.isLoading;
|