feat(mcp): move the MCP server to the v5 API and supermemory 5.0 (#1783)
Some checks are pending
Publish Agent Framework Python / publish (push) Waiting to run

This commit is contained in:
Mahesh Sanikommu 2026-10-09 20:19:02 -07:00 • committed by GitHub
parent 2c46964dfa
commit 552803c018
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
61 changed files with 1146 additions and 6203 deletions

View file

@ -14,7 +14,7 @@ memories, profile, spaces, and interactive MCP Apps.
The space used by an operation resolves in this order:
1. An explicit `containerTag` tool or prompt argument
1. An explicit `namespace` tool or prompt argument
2. The account's durable active space
3. The Supermemory client default, `sm_project_default`
@ -137,7 +137,8 @@ discovery and rejection tests still run.
## Storage And Rollout
`SpaceState` stores only the active space's container tag. It never stores bearer
`SpaceState` stores only the active space's namespace (under the legacy
`activeContainerTag` key, so existing selections survive). It never stores bearer
tokens, MCP client identity, or protocol messages.
The old `SupermemoryMCP` class and binding remain inert for one rollout. This

View file

@ -64,7 +64,7 @@ describeWithAuth("MCP — graph, resources & prompts", () => {
expect(res.contents[0].mimeType).toBe("text/plain")
expect(text).toMatch(/# My Spaces/)
expect(text).toMatch(/Active:/)
expect(text).not.toMatch(/"containerTags":/)
expect(text).not.toMatch(/"namespaces":/)
})
it("gets compact active-space context without prompt arguments", async () => {

View file

@ -219,13 +219,13 @@ export async function recallUntil(
{
tries = 18,
delayMs = 5000,
containerTag = undefined as string | undefined,
namespace = undefined as string | undefined,
} = {},
): Promise<string | null> {
for (let i = 0; i < tries; i++) {
const res = await callTool(client, "search_memory", {
query,
...(containerTag ? { containerTag } : {}),
...(namespace ? { namespace } : {}),
})
const txt = textOf(res)
if (txt.includes(needle)) return txt

View file

@ -18,8 +18,8 @@ type AppView = {
viewId?: string
id?: string
fileName?: string
containerTag?: string
writableTags?: string[]
namespace?: string
writableNamespaces?: string[]
}
async function waitForToolText(
@ -45,7 +45,7 @@ describe.skipIf(!OAUTH_CREDENTIALS_AVAILABLE)(
let session: Session
const createdMemories: Array<{
content: string
containerTag: string
namespace: string
}> = []
beforeAll(async () => {
@ -57,7 +57,7 @@ describe.skipIf(!OAUTH_CREDENTIALS_AVAILABLE)(
await callTool(session.client, "add_memory", {
content: memory.content,
action: "forget",
containerTag: memory.containerTag,
namespace: memory.namespace,
}).catch(() => {})
}
await session?.close()
@ -72,33 +72,33 @@ describe.skipIf(!OAUTH_CREDENTIALS_AVAILABLE)(
expect(launcher.isError).toBeFalsy()
const launcherView = launcher.structuredContent as AppView
const containerTag = launcherView.writableTags?.[0]
const namespace = launcherView.writableNamespaces?.[0]
expect(launcherView.view).toBe("save")
expect(launcherView.viewId).toBeTruthy()
expect(containerTag).toBeTruthy()
if (!launcherView.viewId || !containerTag) {
expect(namespace).toBeTruthy()
if (!launcherView.viewId || !namespace) {
throw new Error("Guided save did not provide a writable space")
}
const saved = await callTool(session.client, "save-memory", {
content,
containerTag,
namespace,
viewId: launcherView.viewId,
})
expect(saved.isError).toBeFalsy()
const savedView = saved.structuredContent as AppView
expect(savedView).toMatchObject({
view: "save-success",
containerTag,
namespace,
})
expect(savedView.id).toBeTruthy()
if (!savedView.id) throw new Error("Save did not return a document ID")
createdMemories.push({ content, containerTag })
createdMemories.push({ content, namespace })
const listedDocument = await waitForToolText(
session,
"list_documents",
{ page: 1, limit: 50, containerTag },
{ page: 1, limit: 50, namespace },
`[${savedView.id}]`,
20,
1000,
@ -108,7 +108,7 @@ describe.skipIf(!OAUTH_CREDENTIALS_AVAILABLE)(
const document = await waitForToolText(
session,
"get_document",
{ documentId: savedView.id },
{ documentId: savedView.id, namespace },
`Document ID: ${savedView.id}`,
20,
1000,
@ -118,27 +118,11 @@ describe.skipIf(!OAUTH_CREDENTIALS_AVAILABLE)(
const memoriesResult = await callTool(session.client, "list_memories", {
page: 1,
limit: 10,
containerTag: "sm_project_default",
namespace: "sm_project_default",
})
expect(memoriesResult.isError).toBeFalsy()
const memories = textOf(memoriesResult)
expect(memories).toMatch(/active memor(?:y|ies) \(page 1 of \d+/i)
const sourceDocumentId = memories.match(
/Source documents: ([^,\n]+)/,
)?.[1]
expect(sourceDocumentId).toBeTruthy()
if (!sourceDocumentId) {
throw new Error("Listed memory did not include a source document")
}
const sourceDocument = await callTool(session.client, "get_document", {
documentId: sourceDocumentId,
})
expect(sourceDocument.isError).toBeFalsy()
expect(textOf(sourceDocument)).toContain(
`Document ID: ${sourceDocumentId}`,
)
}, 60_000)
it("uploads and reads a text document", async () => {
@ -149,22 +133,23 @@ describe.skipIf(!OAUTH_CREDENTIALS_AVAILABLE)(
expect(launcher.isError).toBeFalsy()
const launcherView = launcher.structuredContent as AppView
const containerTag = launcherView.writableTags?.[0]
const namespace = launcherView.writableNamespaces?.[0]
expect(launcherView.view).toBe("upload")
expect(launcherView.viewId).toBeTruthy()
expect(containerTag).toBeTruthy()
if (!launcherView.viewId || !containerTag) {
expect(namespace).toBeTruthy()
if (!launcherView.viewId || !namespace) {
throw new Error("Upload did not provide a writable space")
}
const prepared = await callTool(session.client, "prepare-file-upload")
const prepared = await callTool(session.client, "prepare-file-upload", {
namespace,
})
expect(prepared.isError).toBeFalsy()
const preparation = uploadPreparationSchema.parse(
prepared.structuredContent,
)
const formData = new FormData()
formData.append("file", new Blob([fileContent]), fileName)
formData.append("containerTag", containerTag)
formData.append(
"metadata",
JSON.stringify({ sm_source: "supermemory-mcp" }),
@ -183,7 +168,7 @@ describe.skipIf(!OAUTH_CREDENTIALS_AVAILABLE)(
const document = await waitForToolText(
session,
"get_document",
{ documentId: uploaded.id },
{ documentId: uploaded.id, namespace },
`Document ID: ${uploaded.id}`,
20,
1000,

View file

@ -11,17 +11,17 @@ import {
describe.skipIf(!OAUTH_CREDENTIALS_AVAILABLE)("MCP — memory behaviors", () => {
let s: Session
const created: Array<{ content: string; containerTag?: string }> = []
const created: Array<{ content: string; namespace?: string }> = []
beforeAll(async () => {
s = await connect()
})
afterAll(async () => {
for (const { content, containerTag } of created) {
for (const { content, namespace } of created) {
await callTool(s.client, "add_memory", {
content,
action: "forget",
...(containerTag ? { containerTag } : {}),
...(namespace ? { namespace } : {}),
}).catch(() => {})
}
await s?.close()
@ -90,32 +90,32 @@ describe.skipIf(!OAUTH_CREDENTIALS_AVAILABLE)("MCP — memory behaviors", () =>
expect(textOf(forgotten)).toMatch(/forgot|No matching memory found/i)
}, 120_000)
it("containerTag scopes memories (isolation)", async () => {
// Fixed tags (not per-run UUIDs) so the test doesn't mint a new project each run.
const tagA = "sm_e2e_scope_a"
const tagB = "sm_e2e_scope_b"
it("namespace scopes memories (isolation)", async () => {
// Fixed namespaces (not per-run UUIDs) so the test doesn't mint a new one each run.
const namespaceA = "sm_e2e_scope_a"
const namespaceB = "sm_e2e_scope_b"
const marker = `sc-${randomUUID()}`
const content = `e2e scoping. token=${marker}. Project color is teal.`
created.push({ content, containerTag: tagA })
created.push({ content, namespace: namespaceA })
await callTool(s.client, "add_memory", {
content,
action: "save",
containerTag: tagA,
namespace: namespaceA,
})
const inA = await recallUntil(s.client, "project color teal", marker, {
containerTag: tagA,
namespace: namespaceA,
})
expect(inA, "marker should be found in its own container").not.toBeNull()
expect(inA, "marker should be found in its own namespace").not.toBeNull()
// Same query scoped to a different container must NOT see it.
// Same query scoped to a different namespace must NOT see it.
const leaked = await recallUntil(s.client, "project color teal", marker, {
containerTag: tagB,
namespace: namespaceB,
tries: 3,
delayMs: 3000,
})
expect(leaked, "marker leaked across containers").toBeNull()
expect(leaked, "marker leaked across namespaces").toBeNull()
}, 120_000)
it("returns an error result for a missing required argument", async () => {

View file

@ -12,7 +12,7 @@ const propsOf = (tools: ToolLike[], name: string): Record<string, unknown> =>
const describeWithAuth = describe.skipIf(!OAUTH_CREDENTIALS_AVAILABLE)
describeWithAuth("MCP - space scoping", () => {
it("keeps per-call containerTag overrides when an obsolete header is sent", async () => {
it("keeps per-call namespace overrides when an obsolete header is sent", async () => {
const scoped = await connect({
headers: { "x-sm-project": "obsolete-root-scope" },
})
@ -21,17 +21,13 @@ describeWithAuth("MCP - space scoping", () => {
const scopedTools = (await scoped.client.listTools()).tools
const plainTools = (await plain.client.listTools()).tools
expect(propsOf(plainTools, "add_memory")).toHaveProperty("containerTag")
expect(propsOf(plainTools, "search_memory")).toHaveProperty(
"containerTag",
)
expect(propsOf(plainTools, "get_profile")).toHaveProperty("containerTag")
expect(propsOf(plainTools, "add_memory")).toHaveProperty("namespace")
expect(propsOf(plainTools, "search_memory")).toHaveProperty("namespace")
expect(propsOf(plainTools, "get_profile")).toHaveProperty("namespace")
expect(propsOf(scopedTools, "add_memory")).toHaveProperty("containerTag")
expect(propsOf(scopedTools, "search_memory")).toHaveProperty(
"containerTag",
)
expect(propsOf(scopedTools, "get_profile")).toHaveProperty("containerTag")
expect(propsOf(scopedTools, "add_memory")).toHaveProperty("namespace")
expect(propsOf(scopedTools, "search_memory")).toHaveProperty("namespace")
expect(propsOf(scopedTools, "get_profile")).toHaveProperty("namespace")
} finally {
await scoped.close()
await plain.close()

View file

@ -25,20 +25,20 @@ describe.skipIf(!OAUTH_CREDENTIALS_AVAILABLE)(
expect(result.isError).toBeFalsy()
const content = result.structuredContent as {
view?: string
containerTags?: Array<{ containerTag: string }>
assignedTags?: Array<{
containerTag: string
namespaces?: Array<{ namespace: string }>
assignedNamespaces?: Array<{
namespace: string
permission: "read" | "write"
}>
}
expect(content.view).toBe("picker")
expect(Array.isArray(content.containerTags)).toBe(true)
expect(content.assignedTags).toHaveLength(
content.containerTags?.length ?? 0,
expect(Array.isArray(content.namespaces)).toBe(true)
expect(content.assignedNamespaces).toHaveLength(
content.namespaces?.length ?? 0,
)
expect(
content.assignedTags?.every((tag) =>
["read", "write"].includes(tag.permission),
content.assignedNamespaces?.every((access) =>
["read", "write"].includes(access.permission),
),
).toBe(true)
})
@ -46,18 +46,18 @@ describe.skipIf(!OAUTH_CREDENTIALS_AVAILABLE)(
it("shares the selected space across MCP transport sessions", async () => {
const picker = await callTool(session.client, "select-space")
const pickerContent = picker.structuredContent as {
containerTags?: Array<{ containerTag: string }>
namespaces?: Array<{ namespace: string }>
}
const firstTag = pickerContent.containerTags?.[0]?.containerTag
expect(firstTag).toBeTruthy()
const firstNamespace = pickerContent.namespaces?.[0]?.namespace
expect(firstNamespace).toBeTruthy()
const result = await callTool(session.client, "set-active-tag", {
containerTag: firstTag,
namespace: firstNamespace,
})
expect(result.isError).toBeFalsy()
expect(result.structuredContent).toMatchObject({
view: "confirmation",
containerTag: firstTag,
namespace: firstNamespace,
})
const separateSession = await connect()
@ -65,7 +65,7 @@ describe.skipIf(!OAUTH_CREDENTIALS_AVAILABLE)(
const identity = await callTool(separateSession.client, "who_am_i")
expect(identity.isError).toBeFalsy()
expect(JSON.parse(textOf(identity))).toMatchObject({
activeSpace: firstTag,
activeSpace: firstNamespace,
})
} finally {
await separateSession.close()

View file

@ -39,7 +39,7 @@
"posthog-node": "^5.18.0",
"react": "^19.2.4",
"react-dom": "^19.2.4",
"supermemory": "^4.0.0",
"supermemory": "^5.0.0",
"tailwind-merge": "^3.4.0",
"zod": "^4.4.3"
},

5264
apps/mcp/pnpm-lock.yaml generated

File diff suppressed because it is too large Load diff

View file

@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest"
import type { SessionInfo } from "../../shared/types"
import { effectiveContainerTagAccess } from "./rbac"
import { type SessionInfo, sessionInfoSchema } from "../../shared/types"
import { effectiveNamespaceAccess } from "./rbac"
const baseSession: SessionInfo = {
user: { id: "user_test" },
@ -8,11 +8,11 @@ const baseSession: SessionInfo = {
scope: { type: "full", permission: "write" },
}
describe("effectiveContainerTagAccess", () => {
it("marks every visible tag writable for full access", () => {
expect(effectiveContainerTagAccess(["one", "two"], baseSession)).toEqual([
{ containerTag: "one", permission: "write" },
{ containerTag: "two", permission: "write" },
describe("effectiveNamespaceAccess", () => {
it("marks every visible namespace writable for full access", () => {
expect(effectiveNamespaceAccess(["one", "two"], baseSession)).toEqual([
{ namespace: "one", permission: "write" },
{ namespace: "two", permission: "write" },
])
})
@ -20,15 +20,15 @@ describe("effectiveContainerTagAccess", () => {
const session: SessionInfo = {
...baseSession,
accessType: "restricted",
containerTags: [
{ containerTag: "one", permission: "read" },
{ containerTag: "two", permission: "write" },
namespaces: [
{ namespace: "one", permission: "read" },
{ namespace: "two", permission: "write" },
],
}
expect(effectiveContainerTagAccess(["one", "two"], session)).toEqual([
{ containerTag: "one", permission: "read" },
{ containerTag: "two", permission: "write" },
expect(effectiveNamespaceAccess(["one", "two"], session)).toEqual([
{ namespace: "one", permission: "read" },
{ namespace: "two", permission: "write" },
])
})
@ -42,20 +42,33 @@ describe("effectiveContainerTagAccess", () => {
},
}
expect(effectiveContainerTagAccess(["one"], session)).toEqual([
{ containerTag: "one", permission: "read" },
expect(effectiveNamespaceAccess(["one"], session)).toEqual([
{ namespace: "one", permission: "read" },
])
})
it("treats full-scope read-only grants as read on every tag", () => {
it("treats full-scope read-only grants as read on every namespace", () => {
const session: SessionInfo = {
...baseSession,
scope: { type: "full", permission: "read" },
}
expect(effectiveContainerTagAccess(["one", "two"], session)).toEqual([
{ containerTag: "one", permission: "read" },
{ containerTag: "two", permission: "read" },
expect(effectiveNamespaceAccess(["one", "two"], session)).toEqual([
{ namespace: "one", permission: "read" },
{ namespace: "two", permission: "read" },
])
})
it("reads restricted access from the legacy session field", () => {
const session = sessionInfoSchema.parse({
user: { id: "user_test" },
accessType: "restricted",
containerTags: [{ containerTag: "one", permission: "write" }],
})
expect(session.namespaces).toEqual([
{ namespace: "one", permission: "write" },
])
expect(session).not.toHaveProperty("containerTags")
})
})

View file

@ -1,36 +1,36 @@
import type { ContainerTagAccess, SessionInfo } from "../../shared/types"
import type { NamespaceAccess, SessionInfo } from "../../shared/types"
export function effectiveContainerTagAccess(
containerTags: string[],
export function effectiveNamespaceAccess(
namespaces: string[],
session: SessionInfo,
): ContainerTagAccess[] {
): NamespaceAccess[] {
const memberAccess = new Map(
(session.containerTags ?? []).map((access) => [
access.containerTag,
(session.namespaces ?? []).map((access) => [
access.namespace,
access.permission,
]),
)
const scopedTags = new Set(
const scopedNamespaces = new Set(
session.scope?.tags ?? (session.scope?.tag ? [session.scope.tag] : []),
)
return containerTags.map((containerTag) => {
let permission: ContainerTagAccess["permission"] = "write"
return namespaces.map((namespace) => {
let permission: NamespaceAccess["permission"] = "write"
if (session.accessType === "restricted") {
permission = memberAccess.get(containerTag) ?? "read"
permission = memberAccess.get(namespace) ?? "read"
}
if (session.scope?.permission === "read") {
permission = "read"
} else if (
session.scope?.type === "scoped" &&
scopedTags.size > 0 &&
!scopedTags.has(containerTag)
scopedNamespaces.size > 0 &&
!scopedNamespaces.has(namespace)
) {
permission = "read"
}
return { containerTag, permission }
return { namespace, permission }
})
}

View file

@ -1,65 +1,64 @@
import Supermemory from "supermemory"
import type {
DocumentGetResponse,
DocumentListResponse as SdkDocumentListResponse,
} from "supermemory/resources/documents"
import { z } from "zod"
GetDocumentsResponse,
ListResponseDocumentsItem,
ListResponseMemoriesItem,
ListResponsePagination,
SearchResponseResultsItem,
} from "supermemory"
import {
containerTagSchema,
documentsApiResponseSchema,
memoriesListSchema,
type ContainerTag,
type DocumentMemoryEntry,
type DocumentsApiResponse,
type DocumentWithMemories,
type MemoriesList,
type MemoryEntry,
type MemoryEntryHistory,
type NamespaceInfo,
} from "../../shared/types"
const MAX_CHARS = 200000
export const DEFAULT_PROJECT_ID = "sm_project_default"
export const DEFAULT_NAMESPACE = "sm_project_default"
const FETCH_TIMEOUT_MS = 30_000
const MCP_SOURCE = "supermemory-mcp"
const NAMESPACE_PAGE_LIMIT = 100
// v4 defaults; v5 lowered the threshold to 0.3.
const SEARCH_THRESHOLD = 0.6
// Analytics matches on this text to tag quota errors, keep them in sync.
export const OUT_OF_CREDITS_MESSAGE =
"Out of credits. Top up or upgrade at https://console.supermemory.ai/billing"
export type {
ContainerTag,
DocumentMemoryEntry,
DocumentWithMemories,
DocumentsApiResponse,
NamespaceInfo,
}
export type DocumentSummary = SdkDocumentListResponse["memories"][number]
export type DocumentDetails = DocumentGetResponse
export interface DocumentSummary {
id: string
title: string | null
type: string
status: string
createdAt: string
updatedAt: string
summary: string | null
url: string | null
}
export type DocumentDetails = GetDocumentsResponse
export interface DocumentsListResponse {
documents: DocumentSummary[]
pagination: SdkDocumentListResponse["pagination"]
pagination: ListResponsePagination
}
// Memory-entry shapes live in shared/types so the client parser and the
// listMemories output schema share one definition and can't drift.
export type { MemoryEntry, MemoryEntryHistory }
export type MemoryEntriesResponse = MemoriesList
export type Memory =
| {
id: string
memory: string
similarity: number
title?: string
content?: string
}
| {
id: string
chunk: string
similarity: number
title?: string
content?: string
}
| { id: string; memory: string; similarity: number }
| { id: string; chunk: string; similarity: number }
export interface SearchResult {
results: Memory[]
@ -74,7 +73,6 @@ export interface Profile {
export interface ProfileResponse {
profile: Profile
searchResults?: SearchResult
}
export function getMemoryText(m: Memory): string {
@ -85,35 +83,50 @@ function limitByChars(text: string, maxChars = MAX_CHARS): string {
return text.length > maxChars ? `${text.slice(0, maxChars)}...` : text
}
const sdkResultSchema = z.looseObject({
id: z.string(),
memory: z.string().nullish(),
chunk: z.string().nullish(),
content: z.string().nullish(),
similarity: z.number(),
title: z.string().nullish(),
context: z.string().nullish(),
})
function mapSdkResults(value: unknown): Memory[] {
return z
.array(sdkResultSchema)
.parse(value)
.map((result) => {
const text = limitByChars(
result.content || result.memory || result.chunk || result.context || "",
)
const base = {
function mapSearchResults(results: SearchResponseResultsItem[]): Memory[] {
return results.map((result) => {
if (result.chunk && !result.memory) {
return {
id: result.id,
similarity: result.similarity,
...(result.title ? { title: result.title } : {}),
...(result.content ? { content: result.content } : {}),
chunk: limitByChars(result.chunk),
}
if (result.chunk && !result.memory) {
return { ...base, chunk: text }
}
return { ...base, memory: text }
})
}
return {
id: result.id,
similarity: result.similarity,
memory: limitByChars(result.memory ?? ""),
}
})
}
function mapDocumentSummary(
document: ListResponseDocumentsItem,
): DocumentSummary {
return {
id: document.id,
title: document.title,
type: document.type,
status: document.system.status,
createdAt: document.system.createdAt,
updatedAt: document.system.updatedAt,
summary: document.summary,
url: document.url,
}
}
function mapMemoryEntry(memory: ListResponseMemoriesItem): MemoryEntry {
return {
id: memory.id,
memory: memory.memory,
version: memory.version,
isLatest: memory.isLatest,
isForgotten: memory.isForgotten,
isStatic: memory.isStatic,
isInference: memory.isInference,
createdAt: memory.system.createdAt,
updatedAt: memory.system.updatedAt,
}
}
function objectProperty(value: unknown, key: string): unknown {
@ -122,218 +135,191 @@ function objectProperty(value: unknown, key: string): unknown {
: undefined
}
// API error bodies are JSON like {"error": "..."} — unwrap them so users see
// the real reason instead of raw JSON or a generic fallback.
// Unwrap {"error": "..."} bodies so users see the real reason, not raw JSON.
function extractApiErrorMessage(raw: unknown): string | undefined {
if (typeof raw !== "string" || !raw) return undefined
if (!raw) return undefined
if (typeof raw === "object") {
const error = objectProperty(raw, "error")
if (typeof error === "string" && error) return error
const message = objectProperty(raw, "message")
if (typeof message === "string" && message) return message
return undefined
}
if (typeof raw !== "string") return undefined
try {
const parsed = JSON.parse(raw) as { error?: unknown; message?: unknown }
if (typeof parsed.error === "string" && parsed.error) return parsed.error
if (typeof parsed.message === "string" && parsed.message)
return parsed.message
} catch {}
return raw
return extractApiErrorMessage(JSON.parse(raw)) ?? raw
} catch {
return raw
}
}
export interface NamespaceSettings {
namespace: string
supportingContext: string | null
createdAt: string
updatedAt: string
}
const isNotFound = (error: unknown): boolean => {
const e = error as { statusCode?: number; status?: number }
return e?.statusCode === 404 || e?.status === 404
}
export class SupermemoryClient {
private client: Supermemory
private containerTag: string
private hasExplicitContainerTag: boolean
private namespace: string
private hasExplicitNamespace: boolean
private bearerToken: string
private apiUrl: string
constructor(
bearerToken: string,
containerTag?: string,
namespace?: string,
apiUrl = "https://api.supermemory.ai",
) {
this.bearerToken = bearerToken
this.apiUrl = apiUrl
this.client = new Supermemory({
apiKey: bearerToken,
baseURL: apiUrl,
timeout: FETCH_TIMEOUT_MS,
defaultHeaders: { "x-sm-source": MCP_SOURCE },
baseUrl: apiUrl,
timeoutInSeconds: FETCH_TIMEOUT_MS / 1000,
headers: { "x-sm-source": MCP_SOURCE },
})
this.hasExplicitContainerTag = Boolean(containerTag)
this.containerTag = containerTag || DEFAULT_PROJECT_ID
this.hasExplicitNamespace = Boolean(namespace)
this.namespace = namespace || DEFAULT_NAMESPACE
}
async createMemory(
content: string,
): Promise<{ id: string; status: string; containerTag: string }> {
): Promise<{ id: string; status: string; namespace: string }> {
try {
const result = await this.client.add({
const result = await this.client.add(this.namespace, {
content,
containerTag: this.containerTag,
metadata: { sm_source: MCP_SOURCE },
})
return {
id: result.id,
status: "queued",
containerTag: this.containerTag,
status: result.status,
namespace: this.namespace,
}
} catch (error) {
this.handleOperationError("Create memory request", error)
}
}
// v5 has no exact-content forget: preview semantic matches, then forget the best one by ID.
async forgetMemory(
content: string,
): Promise<{ success: boolean; message: string; containerTag: string }> {
): Promise<{ success: boolean; message: string; namespace: string }> {
try {
try {
const result = await this.client.memories.forget({
content,
containerTag: this.containerTag,
})
return {
success: true,
message: `Successfully forgot memory (exact match) with ID: ${result.id}`,
containerTag: this.containerTag,
}
} catch (error: unknown) {
const status = objectProperty(error, "status")
if (status !== 404) throw error
}
const SIMILARITY_THRESHOLD = 0.85
const searchResult = await this.search(
content,
5,
SIMILARITY_THRESHOLD,
this.containerTag,
const preview = await this.client.memories.forgetMatching(
this.namespace,
{ query: content, dryRun: true },
)
if (searchResult.results.length === 0) {
const match = preview.matches[0]
if (!match) {
return {
success: false,
message: "No matching memory found to forget.",
containerTag: this.containerTag,
namespace: this.namespace,
}
}
const memoryToDelete = searchResult.results.find((r) => "memory" in r)
if (!memoryToDelete) {
const result = await this.client.memories.forget(this.namespace, {
ids: [match.id],
})
if (result.count === 0) {
const reason = result.errors[0]?.error ?? "unknown error"
return {
success: false,
message: "No matching memory found (only chunks matched).",
containerTag: this.containerTag,
message: `Could not forget memory ${match.id}: ${reason}`,
namespace: this.namespace,
}
}
await this.client.memories.forget({
id: memoryToDelete.id,
containerTag: this.containerTag,
})
const memoryText =
getMemoryText(memoryToDelete) || memoryToDelete.content || ""
return {
success: true,
message: `Forgot similar memory (similarity: ${memoryToDelete.similarity.toFixed(2)}): "${limitByChars(memoryText, 100)}"`,
containerTag: this.containerTag,
message: `Forgot memory (ID: ${match.id}): "${limitByChars(match.memory, 100)}"`,
namespace: this.namespace,
}
} catch (error) {
this.handleOperationError("Forget memory request", error)
}
}
async search(
query: string,
limit = 10,
threshold?: number,
containerTagOverride?: string,
): Promise<SearchResult> {
async search(query: string, limit = 10): Promise<SearchResult> {
try {
const containerTag =
containerTagOverride ??
(this.hasExplicitContainerTag ? this.containerTag : undefined)
const result = await this.client.search.memories({
q: query,
const result = await this.client.search(this.namespace, {
query,
limit,
...(containerTag ? { containerTag } : {}),
searchMode: "hybrid",
threshold,
threshold: SEARCH_THRESHOLD,
})
const results = mapSearchResults(result.results)
return {
results: mapSdkResults(result.results),
total: result.total,
timing: result.timing,
results,
total: results.length,
timing: result.searchTime,
}
} catch (error) {
this.handleOperationError("Search request", error)
}
}
async getProfile(query?: string): Promise<ProfileResponse> {
if (!this.hasExplicitContainerTag) {
return {
profile: {
static: [],
dynamic: [],
},
}
async getProfile(): Promise<ProfileResponse> {
if (!this.hasExplicitNamespace) {
return { profile: { static: [], dynamic: [] } }
}
try {
const result = await this.client.profile({
containerTag: this.containerTag,
q: query,
})
const response: ProfileResponse = {
const result = await this.client.profile(this.namespace)
return {
profile: {
static: result.profile?.static || [],
dynamic: result.profile?.dynamic || [],
static: result.profile.static.map((fact) => fact.memory),
dynamic: result.profile.dynamic.map((fact) => fact.memory),
},
}
if (result.searchResults) {
response.searchResults = {
results: mapSdkResults(result.searchResults.results),
total: result.searchResults.total,
timing: result.searchResults.timing,
}
}
return response
} catch (error) {
this.handleOperationError("Profile request", error)
}
}
async listContainerTags(): Promise<ContainerTag[]> {
// v5 get returns settings only (no counts); null means missing or no access
async getNamespace(namespace: string): Promise<NamespaceSettings | null> {
try {
const signal = AbortSignal.timeout(FETCH_TIMEOUT_MS)
const response = await fetch(`${this.apiUrl}/v3/container-tags/list`, {
method: "GET",
headers: {
Authorization: `Bearer ${this.bearerToken}`,
"Content-Type": "application/json",
"x-sm-source": MCP_SOURCE,
},
signal,
})
if (!response.ok) {
if (response.status === 401) {
throw new Error("Authentication failed. Please re-authenticate.")
}
throw new Error(
`Failed to fetch container tags: ${response.statusText}`,
)
const entry = await this.client.namespaces.get(namespace)
return {
namespace: entry.namespace,
supportingContext: entry.supportingContext,
createdAt: entry.system.createdAt,
updatedAt: entry.system.updatedAt,
}
} catch (error) {
if (isNotFound(error)) return null
this.handleError(error)
}
}
return z.array(containerTagSchema).parse(await response.json())
// One page is enough for pickers; single-namespace reads use getNamespace
async listNamespaces(limit = NAMESPACE_PAGE_LIMIT): Promise<NamespaceInfo[]> {
try {
const result = await this.client.namespaces.list({ page: 1, limit })
return result.namespaces.map((entry) => ({
id: entry.id,
namespace: entry.namespace,
description: entry.description,
documentCount: entry.documentCount,
memoryCount: entry.memoryCount,
createdAt: entry.system.createdAt,
updatedAt: entry.system.updatedAt,
}))
} catch (error) {
this.handleError(error)
}
}
async getDocuments(
containerTags?: string[],
// v5 has no graph route; this stays on the legacy endpoint until one ships.
async getGraphDocuments(
page = 1,
limit = 200,
options?: { signal?: AbortSignal },
@ -352,7 +338,7 @@ export class SupermemoryClient {
limit,
sort: "createdAt",
order: "desc",
containerTags,
containerTags: [this.namespace],
}),
signal,
})
@ -370,17 +356,14 @@ export class SupermemoryClient {
async listDocuments(page = 1, limit = 50): Promise<DocumentsListResponse> {
try {
const result = await this.client.documents.list({
containerTags: [this.containerTag],
const result = await this.client.list(this.namespace, "documents", {
page,
limit,
sort: "createdAt",
order: "desc",
includeContent: false,
})
return {
documents: result.memories ?? [],
documents: result.documents.map(mapDocumentSummary),
pagination: result.pagination,
}
} catch (error) {
@ -390,7 +373,7 @@ export class SupermemoryClient {
async getDocument(id: string): Promise<DocumentDetails> {
try {
return await this.client.documents.get(id)
return await this.client.documents.get(this.namespace, id)
} catch (error) {
this.handleError(error)
}
@ -401,46 +384,36 @@ export class SupermemoryClient {
limit = 50,
): Promise<MemoryEntriesResponse> {
try {
const response = await fetch(`${this.apiUrl}/v4/memories/list`, {
method: "POST",
headers: {
Authorization: `Bearer ${this.bearerToken}`,
"Content-Type": "application/json",
"x-sm-source": MCP_SOURCE,
},
body: JSON.stringify({
containerTags: [this.containerTag],
page,
limit,
sort: "createdAt",
order: "desc",
}),
signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
const result = await this.client.list(this.namespace, "memories", {
page,
limit,
sort: "createdAt",
order: "desc",
})
if (!response.ok) {
const message = extractApiErrorMessage(await response.text())
throw Object.assign(new Error(message ?? ""), {
status: response.status,
})
return {
memoryEntries: result.memories.map(mapMemoryEntry),
pagination: {
currentPage: result.pagination.currentPage,
limit: result.pagination.limit ?? limit,
totalItems: result.pagination.totalItems,
totalPages: result.pagination.totalPages,
},
}
return memoriesListSchema.parse(await response.json())
} catch (error) {
this.handleError(error)
}
}
private handleError(error: unknown): never {
// Handle request timeout (AbortSignal.timeout or explicit abort)
if (
error instanceof Error &&
(error.name === "AbortError" || error.name === "TimeoutError")
(error.name === "AbortError" ||
error.name === "TimeoutError" ||
error.name === "SupermemoryTimeoutError")
) {
throw new Error("Request to Supermemory API timed out")
}
// Handle network/fetch errors
if (error instanceof TypeError) {
if (
error.message.includes("fetch") ||
@ -450,9 +423,17 @@ export class SupermemoryClient {
}
}
const status = objectProperty(error, "status")
// SDK errors carry statusCode and body; raw fetch errors carry status and message.
const statusCode = objectProperty(error, "statusCode")
const status =
typeof statusCode === "number"
? statusCode
: objectProperty(error, "status")
if (typeof status === "number") {
const message = extractApiErrorMessage(objectProperty(error, "message"))
const message =
typeof statusCode === "number"
? extractApiErrorMessage(objectProperty(error, "body"))
: extractApiErrorMessage(objectProperty(error, "message"))
switch (status) {
case 400:
case 422:

View file

@ -132,15 +132,7 @@ export function getDocumentContent(document: DocumentDetails): {
content: string | null
truncated: boolean
} {
let content: string | null = null
if (typeof document.raw === "string" && document.raw.trim()) {
content = document.raw
} else if (document.raw !== null && document.raw !== undefined) {
content = JSON.stringify(document.raw, null, 2)
} else if (document.content?.trim()) {
content = document.content
}
const content = document.content?.trim() ? document.content : null
if (!content) return { content: null, truncated: false }
const truncated = content.length > MAX_DOCUMENT_CONTENT_CHARS
return {
@ -155,12 +147,11 @@ export function formatDocument(document: DocumentDetails): string {
`# ${title}`,
`Document ID: ${document.id}`,
`Type: ${document.type}`,
`Status: ${document.status}`,
`Created: ${document.createdAt}`,
`Updated: ${document.updatedAt}`,
`Status: ${document.system.status}`,
`Created: ${document.system.createdAt}`,
`Updated: ${document.system.updatedAt}`,
]
if (document.url) parts.push(`URL: ${document.url}`)
if (document.summary?.trim()) {
parts.push("", "## Summary", compactText(document.summary, 4_000))
}

View file

@ -273,13 +273,14 @@ app.post("/upload/:uploadId", async (c) => {
const uploadState = c.env.SPACE_STATE.getByName(uploadStateName(uploadId))
const session = await uploadState.consumeUploadSession(uploadToken)
if (!session) {
if (!session?.namespace) {
return c.json({ error: "Invalid or expired upload session" }, 401)
}
const apiUrl = (c.env.API_URL || DEFAULT_API_URL).replace(/\/+$/, "")
try {
const response = await fetch(`${apiUrl}/v3/documents/file`, {
const namespace = encodeURIComponent(session.namespace)
const response = await fetch(`${apiUrl}/ns/${namespace}/document/file`, {
method: "POST",
headers: {
Authorization: `Bearer ${session.bearerToken}`,

View file

@ -1,12 +1,12 @@
import { z } from "zod"
export const containerTagSchema = z
export const namespaceSchema = z
.string()
.min(1, "Container tag is required")
.max(128, "Container tag exceeds maximum length")
.min(1, "Namespace is required")
.max(128, "Namespace exceeds maximum length")
.describe("Space key returned by list_spaces")
export const optionalContainerTagSchema = containerTagSchema
export const optionalNamespaceSchema = namespaceSchema
.optional()
.describe(
"Space key to use for this call. If the user names a space, call list_spaces to resolve its key and pass it here. If no space is named, omit this field so the server uses the active space or account default.",

View file

@ -1,11 +1,10 @@
import type { McpServer } from "@modelcontextprotocol/server"
import { DEFAULT_PROJECT_ID, type SupermemoryClient } from "../client"
import { DEFAULT_NAMESPACE, type SupermemoryClient } from "../client"
import {
compactDescription,
formatFactSection,
formatSpaceRow,
sortSpaces,
spaceDisplayName,
spaceMetadata,
} from "../space-presentation"
@ -14,8 +13,8 @@ const RECENT_SPACE_LIMIT = 3
export function registerContextPrompt(
server: McpServer,
getClient: (tag?: string) => SupermemoryClient,
resolveContainerTag: () => Promise<string | undefined>,
getClient: (namespace?: string) => SupermemoryClient,
resolveNamespace: () => Promise<string | undefined>,
) {
server.registerPrompt(
"context",
@ -24,20 +23,19 @@ export function registerContextPrompt(
},
async () => {
try {
const selectedTag = await resolveContainerTag()
const activeKey = selectedTag ?? DEFAULT_PROJECT_ID
const selectedNamespace = await resolveNamespace()
const activeKey = selectedNamespace ?? DEFAULT_NAMESPACE
const [profileResult, spaces] = await Promise.all([
getClient(activeKey).getProfile(),
getClient().listContainerTags(),
getClient().listNamespaces(),
])
const activeSpace = spaces.find(
(space) => space.containerTag === activeKey,
(space) => space.namespace === activeKey,
)
const activeLabel = spaceDisplayName(activeSpace, activeKey)
const fallback = selectedTag ? "" : " (default)"
const fallback = selectedNamespace ? "" : " (default)"
const parts: string[] = [
"# Supermemory Context",
`Active space: ${activeLabel} [${activeKey}]${fallback}`,
`Active space: ${activeKey}${fallback}`,
]
if (activeSpace) {
@ -69,7 +67,7 @@ export function registerContextPrompt(
}
const recentSpaces = sortSpaces(spaces, activeKey)
.filter((space) => space.containerTag !== activeKey)
.filter((space) => space.namespace !== activeKey)
.slice(0, RECENT_SPACE_LIMIT)
if (recentSpaces.length > 0) {
parts.push(

View file

@ -1,46 +0,0 @@
import type { McpServer } from "@modelcontextprotocol/server"
import { DEFAULT_PROJECT_ID, type SupermemoryClient } from "../client"
import {
formatSpaceRow,
sortSpaces,
spaceDisplayName,
} from "../space-presentation"
export function registerContainerTagsResource(
server: McpServer,
getClient: () => SupermemoryClient,
resolveContainerTag: () => Promise<string | undefined>,
) {
server.registerResource("My Spaces", "supermemory://spaces", {}, async () => {
const client = getClient()
const [containerTags, selectedTag] = await Promise.all([
client.listContainerTags(),
resolveContainerTag(),
])
const activeKey = selectedTag ?? DEFAULT_PROJECT_ID
const activeSpace = containerTags.find(
(space) => space.containerTag === activeKey,
)
const rows = sortSpaces(containerTags, activeKey).map((space) =>
formatSpaceRow(space, activeKey),
)
const activeLabel = spaceDisplayName(activeSpace, activeKey)
const fallback = selectedTag ? "" : " (default)"
const text = [
"# My Spaces",
`${containerTags.length} available · Active: ${activeLabel} [${activeKey}]${fallback}`,
"",
...rows,
].join("\n")
return {
contents: [
{
uri: "supermemory://spaces",
mimeType: "text/plain",
text,
},
],
}
})
}

View file

@ -0,0 +1,38 @@
import type { McpServer } from "@modelcontextprotocol/server"
import { DEFAULT_NAMESPACE, type SupermemoryClient } from "../client"
import { formatSpaceRow, sortSpaces } from "../space-presentation"
export function registerNamespacesResource(
server: McpServer,
getClient: () => SupermemoryClient,
resolveNamespace: () => Promise<string | undefined>,
) {
server.registerResource("My Spaces", "supermemory://spaces", {}, async () => {
const client = getClient()
const [namespaces, selectedNamespace] = await Promise.all([
client.listNamespaces(),
resolveNamespace(),
])
const activeKey = selectedNamespace ?? DEFAULT_NAMESPACE
const rows = sortSpaces(namespaces, activeKey).map((space) =>
formatSpaceRow(space, activeKey),
)
const fallback = selectedNamespace ? "" : " (default)"
const text = [
"# My Spaces",
`${namespaces.length} available · Active: ${activeKey}${fallback}`,
"",
...rows,
].join("\n")
return {
contents: [
{
uri: "supermemory://spaces",
mimeType: "text/plain",
text,
},
],
}
})
}

View file

@ -1,9 +1,8 @@
import type { McpServer } from "@modelcontextprotocol/server"
import { DEFAULT_PROJECT_ID, type SupermemoryClient } from "../client"
import { DEFAULT_NAMESPACE, type SupermemoryClient } from "../client"
import {
compactDescription,
formatFactSection,
spaceDisplayName,
spaceMetadata,
} from "../space-presentation"
@ -11,28 +10,25 @@ const PROFILE_FACT_LIMIT = 12
export function registerProfileResource(
server: McpServer,
getClient: (containerTag?: string) => SupermemoryClient,
resolveContainerTag: () => Promise<string | undefined>,
getClient: (namespace?: string) => SupermemoryClient,
resolveNamespace: () => Promise<string | undefined>,
) {
server.registerResource(
"Active Space Profile",
"supermemory://profile",
{},
async () => {
const selectedTag = await resolveContainerTag()
const activeKey = selectedTag ?? DEFAULT_PROJECT_ID
const selectedNamespace = await resolveNamespace()
const activeKey = selectedNamespace ?? DEFAULT_NAMESPACE
const [profileResult, spaces] = await Promise.all([
getClient(activeKey).getProfile(),
getClient().listContainerTags(),
getClient().listNamespaces(),
])
const activeSpace = spaces.find(
(space) => space.containerTag === activeKey,
)
const activeLabel = spaceDisplayName(activeSpace, activeKey)
const fallback = selectedTag ? "" : " (default)"
const activeSpace = spaces.find((space) => space.namespace === activeKey)
const fallback = selectedNamespace ? "" : " (default)"
const parts: string[] = [
"# Active Space Profile",
`Space: ${activeLabel} [${activeKey}]${fallback}`,
`Space: ${activeKey}${fallback}`,
]
if (activeSpace) {

View file

@ -5,16 +5,16 @@ import {
} from "@modelcontextprotocol/server"
import { instrumentPosthogMcp, type WaitUntil } from "./analytics"
import { fetchSession } from "./auth"
import { DEFAULT_PROJECT_ID, SupermemoryClient } from "./client"
import { DEFAULT_NAMESPACE, SupermemoryClient } from "./client"
import { registerContextPrompt } from "./prompts/context"
import { registerContainerTagsResource } from "./resources/container-tags"
import { registerNamespacesResource } from "./resources/namespaces"
import { registerProfileResource } from "./resources/profile"
import { registerWidgetResource } from "./resources/widget"
import { registerAllTools } from "./tools"
import { errorResult } from "./tools/types"
import type { ActorContext, ServerEnv } from "./types"
import {
resolveContainerTag as resolveSpaceContainerTag,
resolveNamespace as resolveSpaceNamespace,
spaceStateName,
} from "./space"
import { uploadStateName } from "./space-state"
@ -59,16 +59,16 @@ export function createSupermemoryServer(
const apiUrl = env.API_URL || DEFAULT_API_URL
const spaceState = env.SPACE_STATE.getByName(spaceStateName(actor))
const getClient = (containerTag?: string) =>
new SupermemoryClient(actor.bearerToken, containerTag, apiUrl)
const getActiveContainerTag = () => spaceState.getActiveContainerTag()
const setActiveContainerTag = (containerTag: string) =>
spaceState.setActiveContainerTag(containerTag)
const resolveSelectedContainerTag = (explicit?: string) =>
resolveSpaceContainerTag(explicit, getActiveContainerTag)
const resolveContainerTag = async (explicit?: string) =>
(await resolveSelectedContainerTag(explicit)) ?? DEFAULT_PROJECT_ID
const createUploadSession = async () => {
const getClient = (namespace?: string) =>
new SupermemoryClient(actor.bearerToken, namespace, apiUrl)
const getActiveNamespace = () => spaceState.getActiveNamespace()
const setActiveNamespace = (namespace: string) =>
spaceState.setActiveNamespace(namespace)
const resolveSelectedNamespace = (explicit?: string) =>
resolveSpaceNamespace(explicit, getActiveNamespace)
const resolveNamespace = async (explicit?: string) =>
(await resolveSelectedNamespace(explicit)) ?? DEFAULT_NAMESPACE
const createUploadSession = async (namespace: string) => {
const uploadId = crypto.randomUUID()
const uploadToken = [crypto.randomUUID(), crypto.randomUUID()]
.join("")
@ -77,6 +77,7 @@ export function createSupermemoryServer(
const uploadState = env.SPACE_STATE.getByName(uploadStateName(uploadId))
await uploadState.createUploadSession(uploadToken, {
bearerToken: actor.bearerToken,
namespace,
expiresAt,
})
return {
@ -90,22 +91,29 @@ export function createSupermemoryServer(
actor,
getClient,
getSession: () => fetchSession(actor.bearerToken, apiUrl),
resolveContainerTag,
getActiveContainerTag,
setActiveContainerTag,
resolveNamespace,
getActiveNamespace,
setActiveNamespace,
createUploadSession,
getClientInfo: clientInfoFromContext,
errorResult,
})
registerProfileResource(server, getClient, resolveSelectedContainerTag)
registerContainerTagsResource(
// Clients that cached the pre-v5 tool list refetch it on this notice
server.server.oninitialized = () => {
try {
server.sendToolListChanged()
} catch {}
}
registerProfileResource(server, getClient, resolveSelectedNamespace)
registerNamespacesResource(
server,
() => getClient(),
resolveSelectedContainerTag,
resolveSelectedNamespace,
)
registerWidgetResource(server, mcpOrigin)
registerContextPrompt(server, getClient, resolveSelectedContainerTag)
registerContextPrompt(server, getClient, resolveSelectedNamespace)
return server
}

View file

@ -1,17 +1,10 @@
import type { ContainerTag } from "../shared/types"
import type { NamespaceInfo } from "../shared/types"
const DEFAULT_DESCRIPTION_LIMIT = 160
const plural = (count: number, singular: string, pluralForm: string) =>
`${count} ${count === 1 ? singular : pluralForm}`
export function spaceDisplayName(
space: ContainerTag | undefined,
key: string,
): string {
return space?.name || key
}
export function compactDescription(
description: string | null | undefined,
limit = DEFAULT_DESCRIPTION_LIMIT,
@ -39,12 +32,9 @@ export function formatActivityDate(value: string | null): string | undefined {
}).format(date)
}
export function spaceMetadata(space: ContainerTag): string {
const lastActivity = formatActivityDate(space.lastActivityAt ?? null)
export function spaceMetadata(space: NamespaceInfo): string {
const lastActivity = formatActivityDate(space.updatedAt)
const fields = [
space.visibility
? `${space.visibility.charAt(0).toUpperCase()}${space.visibility.slice(1)}`
: undefined,
plural(space.documentCount, "document", "documents"),
plural(space.memoryCount, "memory", "memories"),
lastActivity ? `Last active ${lastActivity}` : undefined,
@ -54,35 +44,28 @@ export function spaceMetadata(space: ContainerTag): string {
}
export function formatSpaceRow(
space: ContainerTag,
space: NamespaceInfo,
activeKey: string,
descriptionLimit = DEFAULT_DESCRIPTION_LIMIT,
): string {
const active = space.containerTag === activeKey ? " · Active" : ""
const active = space.namespace === activeKey ? " · Active" : ""
const metadata = spaceMetadata(space)
const description = compactDescription(space.description, descriptionLimit)
const firstLine =
`- ${spaceDisplayName(space, space.containerTag)} ` +
`[${space.containerTag}]${active}${metadata ? ` · ${metadata}` : ""}`
const firstLine = `- ${space.namespace}${active}${metadata ? ` · ${metadata}` : ""}`
return description ? `${firstLine}\n ${description}` : firstLine
}
export function sortSpaces(
spaces: ContainerTag[],
spaces: NamespaceInfo[],
activeKey: string,
): ContainerTag[] {
): NamespaceInfo[] {
return [...spaces].sort((left, right) => {
if (left.containerTag === activeKey) return -1
if (right.containerTag === activeKey) return 1
const leftTime = left.lastActivityAt
? new Date(left.lastActivityAt).getTime()
: 0
const rightTime = right.lastActivityAt
? new Date(right.lastActivityAt).getTime()
: 0
return rightTime - leftTime
if (left.namespace === activeKey) return -1
if (right.namespace === activeKey) return 1
return (
new Date(right.updatedAt).getTime() - new Date(left.updatedAt).getTime()
)
})
}

View file

@ -1,11 +1,13 @@
import { DurableObject } from "cloudflare:workers"
import { containerTagSchema } from "./container-tag"
import { namespaceSchema } from "./namespace"
const ACTIVE_CONTAINER_TAG_KEY = "activeContainerTag"
// Stored key keeps its legacy name so existing users keep their active space.
const ACTIVE_NAMESPACE_KEY = "activeContainerTag"
const UPLOAD_SESSION_KEY = "uploadSession"
export interface UploadSession {
bearerToken: string
namespace: string
expiresAt: number
}
@ -24,13 +26,15 @@ export function uploadStateName(uploadId: string): string {
}
export class SpaceState extends DurableObject {
async getActiveContainerTag(): Promise<string | undefined> {
return this.ctx.storage.get<string>(ACTIVE_CONTAINER_TAG_KEY)
async getActiveNamespace(): Promise<string | undefined> {
return this.ctx.storage.get<string>(ACTIVE_NAMESPACE_KEY)
}
async setActiveContainerTag(containerTag: string): Promise<void> {
const validatedTag = containerTagSchema.parse(containerTag)
await this.ctx.storage.put(ACTIVE_CONTAINER_TAG_KEY, validatedTag)
async setActiveNamespace(namespace: string): Promise<void> {
await this.ctx.storage.put(
ACTIVE_NAMESPACE_KEY,
namespaceSchema.parse(namespace),
)
}
async createUploadSession(
@ -62,6 +66,7 @@ export class SpaceState extends DurableObject {
await transaction.delete(UPLOAD_SESSION_KEY)
return {
bearerToken: session.bearerToken,
namespace: session.namespace,
expiresAt: session.expiresAt,
}
})

View file

@ -1,6 +1,6 @@
import { describe, expect, it, vi } from "vitest"
import { optionalContainerTagSchema } from "./container-tag"
import { resolveContainerTag, spaceStateName } from "./space"
import { optionalNamespaceSchema } from "./namespace"
import { resolveNamespace, spaceStateName } from "./space"
describe("space application state", () => {
it("keys active state by organization and user without collisions", () => {
@ -20,7 +20,7 @@ describe("space application state", () => {
it("uses an explicit tool argument without reading active state", async () => {
const getActive = vi.fn().mockResolvedValue("active")
await expect(resolveContainerTag("explicit", getActive)).resolves.toBe(
await expect(resolveNamespace("explicit", getActive)).resolves.toBe(
"explicit",
)
expect(getActive).not.toHaveBeenCalled()
@ -28,18 +28,18 @@ describe("space application state", () => {
it("falls back to durable active state and then the client default", async () => {
await expect(
resolveContainerTag(undefined, vi.fn().mockResolvedValue("active")),
resolveNamespace(undefined, vi.fn().mockResolvedValue("active")),
).resolves.toBe("active")
await expect(
resolveContainerTag(undefined, vi.fn().mockResolvedValue(undefined)),
resolveNamespace(undefined, vi.fn().mockResolvedValue(undefined)),
).resolves.toBeUndefined()
})
it("tells the model how to route explicit space requests", () => {
expect(optionalContainerTagSchema.description).toContain(
expect(optionalNamespaceSchema.description).toContain(
"If the user names a space",
)
expect(optionalContainerTagSchema.description).toContain("list_spaces")
expect(optionalContainerTagSchema.description).toContain("active space")
expect(optionalNamespaceSchema.description).toContain("list_spaces")
expect(optionalNamespaceSchema.description).toContain("active space")
})
})

View file

@ -6,9 +6,9 @@ export function spaceStateName(
return `space:${JSON.stringify([actor.organizationId, actor.userId])}`
}
export async function resolveContainerTag(
export async function resolveNamespace(
explicit: string | undefined,
getActiveContainerTag: () => Promise<string | undefined>,
getActiveNamespace: () => Promise<string | undefined>,
): Promise<string | undefined> {
return explicit ?? (await getActiveContainerTag())
return explicit ?? (await getActiveNamespace())
}

View file

@ -1,5 +1,10 @@
import { z } from "zod"
import { optionalContainerTagSchema } from "../container-tag"
import { optionalNamespaceSchema } from "../namespace"
import {
legacyNamespaceInput,
namespaceArg,
withLegacyNamespace,
} from "./compat"
import { MEMORY_TOOL_ANNOTATIONS } from "./annotations"
import { addMemoryOutputSchema, type AddMemoryOutput } from "./output-schemas"
import { textContent, type ToolDeps } from "./types"
@ -11,31 +16,32 @@ export function register(deps: ToolDeps) {
.max(200000, "Content exceeds maximum length")
.describe("The memory content to save or forget"),
action: z.enum(["save", "forget"]).optional().default("save"),
containerTag: optionalContainerTagSchema,
namespace: optionalNamespaceSchema,
...legacyNamespaceInput,
})
deps.server.registerTool(
"add_memory",
{
description:
"Add (save) or forget a memory in the user's ACTIVE space. Defaults to 'save'. The target space is the one the user selected via select-space; pass containerTag only to override it. Use 'forget' when information is outdated or the user asks to remove it.",
"Add (save) or forget a memory in the user's ACTIVE space. Defaults to 'save'. The target space is the one the user selected via select-space; pass namespace only to override it. Use 'forget' when information is outdated or the user asks to remove it.",
inputSchema,
outputSchema: addMemoryOutputSchema,
annotations: MEMORY_TOOL_ANNOTATIONS,
},
async (args) => {
try {
const effectiveTag = await deps.resolveContainerTag(args.containerTag)
const client = deps.getClient(effectiveTag)
const namespace = await deps.resolveNamespace(namespaceArg(args))
const client = deps.getClient(namespace)
if (args.action === "forget") {
const result = await client.forgetMemory(args.content)
const structuredContent: AddMemoryOutput = {
const structuredContent: AddMemoryOutput = withLegacyNamespace({
action: "forget",
success: result.success,
containerTag: result.containerTag,
namespace: result.namespace,
message: result.message,
}
})
return {
content: [textContent(result.message)],
structuredContent,
@ -43,15 +49,15 @@ export function register(deps: ToolDeps) {
}
const result = await client.createMemory(args.content)
const message = `Memory saved (ID: ${result.id}, space: ${result.containerTag})`
const structuredContent: AddMemoryOutput = {
const message = `Memory saved (ID: ${result.id}, space: ${result.namespace})`
const structuredContent: AddMemoryOutput = withLegacyNamespace({
action: "save",
success: true,
containerTag: result.containerTag,
namespace: result.namespace,
message,
id: result.id,
status: result.status,
}
})
return {
content: [textContent(message)],
structuredContent,

View file

@ -0,0 +1,178 @@
import { describe, expect, it, vi } from "vitest"
import { z } from "zod"
import * as addMemory from "./add-memory"
import { namespaceArg, withLegacyView } from "./compat"
import * as listNamespaces from "./list-namespaces"
import * as setActiveTag from "./set-active-tag"
import type { ToolDeps } from "./types"
import { errorResult } from "./types"
type Registered = {
config: { inputSchema: z.ZodTypeAny; outputSchema: z.ZodTypeAny }
cb: (
args: Record<string, unknown>,
context: unknown,
) => Promise<{
structuredContent?: Record<string, unknown>
isError?: boolean
}>
}
function fakeDeps() {
const tools = new Map<string, Registered>()
const client = {
createMemory: vi.fn().mockResolvedValue({
id: "d1",
status: "queued",
namespace: "legacy_ns",
}),
getNamespace: vi.fn().mockImplementation(async (ns: string) =>
ns === "legacy_ns"
? {
namespace: ns,
supportingContext: null,
createdAt: "2026-01-01",
updatedAt: "2026-01-02",
}
: null,
),
listNamespaces: vi.fn().mockResolvedValue([
{
id: "1",
namespace: "legacy_ns",
description: null,
documentCount: 2,
memoryCount: 1,
createdAt: "2026-01-01",
updatedAt: "2026-01-02",
},
]),
}
const deps = {
server: {
registerTool: (name: string, config: unknown, cb: unknown) => {
tools.set(name, { config, cb } as Registered)
},
},
getClient: vi.fn(() => client),
resolveNamespace: vi.fn(async (explicit?: string) => explicit ?? "active"),
setActiveNamespace: vi.fn(async () => {}),
errorResult,
} as unknown as ToolDeps
return { deps, tools, client }
}
// Shape a client that cached the pre-v5 tool list validates against
const legacyAddMemoryOutput = z.object({
action: z.enum(["save", "forget"]),
success: z.boolean(),
containerTag: z.string(),
message: z.string(),
})
describe("containerTag compatibility", () => {
it("prefers namespace and falls back to the deprecated containerTag", () => {
expect(namespaceArg({ namespace: "a", containerTag: "b" })).toBe("a")
expect(namespaceArg({ containerTag: "b" })).toBe("b")
expect(namespaceArg({})).toBeUndefined()
})
it("accepts containerTag input and ignores unknown keys", () => {
const { deps, tools } = fakeDeps()
addMemory.register(deps)
const tool = tools.get("add_memory")
if (!tool) throw new Error("add_memory not registered")
const parsed = tool.config.inputSchema.parse({
content: "hi",
containerTag: "legacy_ns",
somethingElse: 1,
}) as { namespace?: string; containerTag?: string }
expect(parsed.containerTag).toBe("legacy_ns")
expect(parsed.namespace).toBeUndefined()
})
it("routes a containerTag-only call to that namespace and emits both keys", async () => {
const { deps, tools } = fakeDeps()
addMemory.register(deps)
const tool = tools.get("add_memory")
if (!tool) throw new Error("add_memory not registered")
const result = await tool.cb(
{ content: "hi", action: "save", containerTag: "legacy_ns" },
{},
)
expect(deps.getClient).toHaveBeenCalledWith("legacy_ns")
expect(result.structuredContent).toMatchObject({
namespace: "legacy_ns",
containerTag: "legacy_ns",
})
expect(() =>
tool.config.outputSchema.parse(result.structuredContent),
).not.toThrow()
expect(() =>
legacyAddMemoryOutput.parse(result.structuredContent),
).not.toThrow()
})
it("treats containerTag as the required namespace for set-active-tag", async () => {
const { deps, tools } = fakeDeps()
setActiveTag.register(deps)
const tool = tools.get("set-active-tag")
if (!tool) throw new Error("set-active-tag not registered")
const result = await tool.cb({ containerTag: "legacy_ns" }, {})
expect(deps.setActiveNamespace).toHaveBeenCalledWith("legacy_ns")
expect(result.structuredContent).toMatchObject({
view: "confirmation",
namespace: "legacy_ns",
containerTag: "legacy_ns",
})
const missing = await tool.cb({}, {})
expect(missing.isError).toBe(true)
})
it("lists spaces with both keys per item", async () => {
const { deps, tools } = fakeDeps()
listNamespaces.register(deps)
const tool = tools.get("list_spaces")
if (!tool) throw new Error("list_spaces not registered")
const result = await tool.cb({}, {})
expect(result.structuredContent?.spaces).toEqual([
expect.objectContaining({
namespace: "legacy_ns",
containerTag: "legacy_ns",
}),
])
expect(() =>
tool.config.outputSchema.parse(result.structuredContent),
).not.toThrow()
})
it("mirrors renamed view fields under their old names", () => {
const picker = withLegacyView({
view: "picker",
namespaces: [
{
id: "1",
namespace: "ns",
documentCount: 0,
memoryCount: 0,
createdAt: "a",
updatedAt: "b",
},
],
activeNamespace: "ns",
assignedNamespaces: [{ namespace: "ns", permission: "write" }],
})
expect(picker).toMatchObject({
activeTag: "ns",
containerTags: [{ namespace: "ns", containerTag: "ns" }],
assignedTags: [{ namespace: "ns", containerTag: "ns" }],
})
expect(
withLegacyView({
view: "save",
activeNamespace: "ns",
writableNamespaces: ["ns"],
}),
).toMatchObject({ activeTag: "ns", writableTags: ["ns"] })
})
})

View file

@ -0,0 +1,62 @@
import { z } from "zod"
import type {
NamespaceAccess,
NamespaceInfo,
ViewMessage,
} from "../../shared/types"
import { namespaceSchema } from "../namespace"
// Clients that cached the pre-v5 tool list still send and expect containerTag; drop once PostHog shows no containerTag args for 2 weeks.
export const legacyNamespaceInput = {
containerTag: namespaceSchema
.optional()
.describe("Deprecated alias of namespace. Prefer namespace."),
}
export const legacyNamespaceOutput = { containerTag: z.string().optional() }
export const namespaceArg = (args: {
namespace?: string
containerTag?: string
}) => args.namespace ?? args.containerTag
export function withLegacyNamespace<T extends { namespace: string }>(value: T) {
return { ...value, containerTag: value.namespace }
}
export const withLegacyNamespaces = <T extends { namespace: string }>(
values: T[],
) => values.map(withLegacyNamespace)
const legacyAccess = (values: NamespaceAccess[] | null | undefined) =>
values ? withLegacyNamespaces(values) : values
const legacyInfos = (values: NamespaceInfo[]) => withLegacyNamespaces(values)
// Mirrors every renamed view field under its pre-v5 name so cached output schemas still validate.
export function withLegacyView(view: ViewMessage): ViewMessage {
switch (view.view) {
case "picker":
return {
...view,
namespaces: legacyInfos(view.namespaces),
containerTags: legacyInfos(view.namespaces),
activeTag: view.activeNamespace,
assignedNamespaces: legacyAccess(view.assignedNamespaces),
assignedTags: legacyAccess(view.assignedNamespaces),
}
case "save":
case "upload":
return {
...view,
activeTag: view.activeNamespace,
writableTags: view.writableNamespaces,
}
case "confirmation":
case "save-success":
case "upload-success":
return { ...view, containerTag: view.namespace }
case "graph":
return { ...view, containerTag: view.namespace }
}
}

View file

@ -1,7 +1,8 @@
import { z } from "zod"
import { documentsApiResponseSchema } from "../../shared/types"
import { appToolMeta } from "../app-metadata"
import { optionalContainerTagSchema } from "../container-tag"
import { optionalNamespaceSchema } from "../namespace"
import { legacyNamespaceInput, namespaceArg } from "./compat"
import { READ_ONLY_TOOL_ANNOTATIONS } from "./annotations"
import { textContent, type ToolDeps } from "./types"
@ -11,7 +12,8 @@ export function register(deps: ToolDeps) {
{
description: "Fetch documents with memories for graph display",
inputSchema: z.object({
containerTag: optionalContainerTagSchema,
namespace: optionalNamespaceSchema,
...legacyNamespaceInput,
page: z.number().int().min(1).max(10_000).optional().default(1),
limit: z.number().int().min(1).max(1_000).optional().default(200),
}),
@ -21,13 +23,9 @@ export function register(deps: ToolDeps) {
},
async (args) => {
try {
const effectiveTag = await deps.resolveContainerTag(args.containerTag)
const client = deps.getClient(effectiveTag)
const data = await client.getDocuments(
[effectiveTag],
args.page,
args.limit,
)
const namespace = await deps.resolveNamespace(namespaceArg(args))
const client = deps.getClient(namespace)
const data = await client.getGraphDocuments(args.page, args.limit)
return {
content: [

View file

@ -1,5 +1,11 @@
import { z } from "zod"
import { formatDocument, getDocumentContent } from "../format"
import { optionalNamespaceSchema } from "../namespace"
import {
legacyNamespaceInput,
namespaceArg,
withLegacyNamespace,
} from "./compat"
import { READ_ONLY_TOOL_ANNOTATIONS } from "./annotations"
import {
getDocumentOutputSchema,
@ -14,6 +20,8 @@ export function register(deps: ToolDeps) {
.min(1, "Document ID is required")
.max(255, "Document ID exceeds maximum length")
.describe("Document ID returned by list_documents or a memory result"),
namespace: optionalNamespaceSchema,
...legacyNamespaceInput,
})
deps.server.registerTool(
@ -21,30 +29,31 @@ export function register(deps: ToolDeps) {
{
title: "Get Document",
description:
"Read one stored document by ID from any space you can access, including its summary and available content. Use list_documents to discover document IDs.",
"Read one stored document by ID from one space, including its summary and available content. Use list_documents to discover document IDs. When the document is in a named space, resolve it with list_spaces and pass namespace; otherwise use the active space.",
inputSchema,
outputSchema: getDocumentOutputSchema,
annotations: READ_ONLY_TOOL_ANNOTATIONS,
},
async (args) => {
try {
const client = deps.getClient()
const namespace = await deps.resolveNamespace(namespaceArg(args))
const client = deps.getClient(namespace)
const document = await client.getDocument(args.documentId)
const { content, truncated } = getDocumentContent(document)
const structuredContent: GetDocumentOutput = {
const structuredContent: GetDocumentOutput = withLegacyNamespace({
namespace,
document: {
id: document.id,
title: document.title,
type: document.type,
status: document.status,
createdAt: document.createdAt,
updatedAt: document.updatedAt,
url: document.url ?? null,
status: document.system.status,
createdAt: document.system.createdAt,
updatedAt: document.system.updatedAt,
summary: document.summary,
content,
contentTruncated: truncated,
},
}
})
return {
content: [textContent(formatDocument(document))],

View file

@ -1,5 +1,10 @@
import { z } from "zod"
import { optionalContainerTagSchema } from "../container-tag"
import { optionalNamespaceSchema } from "../namespace"
import {
legacyNamespaceInput,
namespaceArg,
withLegacyNamespace,
} from "./compat"
import { formatFactSection } from "../space-presentation"
import { READ_ONLY_TOOL_ANNOTATIONS } from "./annotations"
import { getProfileOutputSchema, type GetProfileOutput } from "./output-schemas"
@ -7,7 +12,8 @@ import { textContent, type ToolDeps } from "./types"
export function register(deps: ToolDeps) {
const inputSchema = z.object({
containerTag: optionalContainerTagSchema,
namespace: optionalNamespaceSchema,
...legacyNamespaceInput,
})
deps.server.registerTool(
@ -15,15 +21,15 @@ export function register(deps: ToolDeps) {
{
title: "Get Profile",
description:
"Get the stable and recent profile for one space — long-lived facts plus recent context. search_memory does not include this. After searching, call this if matching memories are not enough and you need who-the-user-is, preferences, or recent context. When the user names a space, resolve it with list_spaces and pass containerTag; otherwise use the active space. Use who_am_i for account identity and access, not profile facts.",
"Get the stable and recent profile for one space — long-lived facts plus recent context. search_memory does not include this. After searching, call this if matching memories are not enough and you need who-the-user-is, preferences, or recent context. When the user names a space, resolve it with list_spaces and pass namespace; otherwise use the active space. Use who_am_i for account identity and access, not profile facts.",
inputSchema,
outputSchema: getProfileOutputSchema,
annotations: READ_ONLY_TOOL_ANNOTATIONS,
},
async (args) => {
try {
const effectiveTag = await deps.resolveContainerTag(args.containerTag)
const profileResult = await deps.getClient(effectiveTag).getProfile()
const namespace = await deps.resolveNamespace(namespaceArg(args))
const profileResult = await deps.getClient(namespace).getProfile()
const profile = {
static: profileResult.profile.static,
dynamic: profileResult.profile.dynamic,
@ -46,10 +52,10 @@ export function register(deps: ToolDeps) {
parts.push("No profile facts are available for this space yet.")
}
const structuredContent: GetProfileOutput = {
containerTag: effectiveTag,
const structuredContent: GetProfileOutput = withLegacyNamespace({
namespace,
profile,
}
})
return {
content: [textContent(parts.join("\n"))],

View file

@ -1,8 +1,9 @@
import { z } from "zod"
import { saveViewSchema, type ViewMessage } from "../../shared/types"
import { appResultMeta, appToolMeta } from "../app-metadata"
import { effectiveContainerTagAccess } from "../auth/rbac"
import { effectiveNamespaceAccess } from "../auth/rbac"
import { READ_ONLY_TOOL_ANNOTATIONS } from "./annotations"
import { withLegacyView } from "./compat"
import { textContent, type ToolDeps } from "./types"
export function register(deps: ToolDeps) {
@ -27,25 +28,25 @@ export function register(deps: ToolDeps) {
try {
const { prefill } = args
const viewId = crypto.randomUUID()
const [activeTag, tags, session] = await Promise.all([
deps.getActiveContainerTag(),
deps.getClient().listContainerTags(),
const [activeNamespace, namespaces, session] = await Promise.all([
deps.getActiveNamespace(),
deps.getClient().listNamespaces(),
deps.getSession(),
])
const writableTags = effectiveContainerTagAccess(
tags.map((tag) => tag.containerTag),
const writableNamespaces = effectiveNamespaceAccess(
namespaces.map((entry) => entry.namespace),
session,
)
.filter((access) => access.permission === "write")
.map((access) => access.containerTag)
.map((access) => access.namespace)
const sc: ViewMessage = {
const sc: ViewMessage = withLegacyView({
view: "save",
viewId,
activeTag,
writableTags,
activeNamespace,
writableNamespaces,
prefill,
}
})
return {
content: [textContent("Opening memory save form...")],

View file

@ -3,7 +3,7 @@ import * as fetchGraphData from "./fetch-graph-data"
import * as getDocument from "./get-document"
import * as getProfile from "./get-profile"
import * as guidedSave from "./guided-save"
import * as listContainerTags from "./list-container-tags"
import * as listNamespaces from "./list-namespaces"
import * as listDocuments from "./list-documents"
import * as listMemories from "./list-memories"
import * as memoryGraph from "./memory-graph"
@ -61,7 +61,7 @@ export function registerAllTools(toolDeps: ToolDeps) {
listDocuments.register(deps)
getDocument.register(deps)
listMemories.register(deps)
listContainerTags.register(deps)
listNamespaces.register(deps)
whoAmI.register(deps)
selectSpace.register(deps)
setActiveTag.register(deps)

View file

@ -1,52 +0,0 @@
import { z } from "zod"
import { listSpacesOutputSchema } from "../../shared/types"
import { READ_ONLY_TOOL_ANNOTATIONS } from "./annotations"
import { textContent, type ToolDeps } from "./types"
export function register(deps: ToolDeps) {
deps.server.registerTool(
"list_spaces",
{
description:
"List the spaces available to the user. Returns each space's name, key, emoji, document/memory counts, and last activity. Use this first to resolve a named space before calling a space-aware tool, or when the user asks which space may contain something. The list is auto-filtered to spaces the user can access.",
inputSchema: z.object({}),
outputSchema: listSpacesOutputSchema,
annotations: READ_ONLY_TOOL_ANNOTATIONS,
},
async () => {
try {
const tags = await deps.getClient().listContainerTags()
const spaces = tags.map((tag) => ({
name: tag.name,
containerTag: tag.containerTag,
description: tag.description,
visibility: tag.visibility,
emoji: tag.emoji,
documentCount: tag.documentCount,
memoryCount: tag.memoryCount,
lastActivityAt: tag.lastActivityAt,
}))
if (tags.length === 0) {
return {
content: [textContent("No spaces found.")],
structuredContent: { spaces, count: 0 },
}
}
const lines = tags.map((t) => {
const display = t.emoji ? `${t.emoji} ${t.name}` : t.name
const counts = `(${t.documentCount} docs, ${t.memoryCount} memories)`
return `- ${display} [${t.containerTag}] ${counts}`
})
return {
content: [textContent(`Available spaces:\n${lines.join("\n")}`)],
structuredContent: { spaces, count: spaces.length },
}
} catch (error) {
return deps.errorResult(error)
}
},
)
}

View file

@ -1,5 +1,6 @@
import { z } from "zod"
import { optionalContainerTagSchema } from "../container-tag"
import { optionalNamespaceSchema } from "../namespace"
import { legacyNamespaceInput, namespaceArg } from "./compat"
import { formatDocumentsList } from "../format"
import { READ_ONLY_TOOL_ANNOTATIONS } from "./annotations"
import {
@ -25,7 +26,8 @@ export function register(deps: ToolDeps) {
.optional()
.default(10)
.describe("Documents per page (default 10, max 50)"),
containerTag: optionalContainerTagSchema,
namespace: optionalNamespaceSchema,
...legacyNamespaceInput,
})
deps.server.registerTool(
@ -33,15 +35,15 @@ export function register(deps: ToolDeps) {
{
title: "List Documents",
description:
"List documents in one space with their IDs, titles, types, processing status, dates, and summaries. This does not return full document content; use get_document with an ID from this result to read one document. When the user names a space, resolve it with list_spaces and pass containerTag; otherwise use the active space.",
"List documents in one space with their IDs, titles, types, processing status, dates, and summaries. This does not return full document content; use get_document with an ID from this result to read one document. When the user names a space, resolve it with list_spaces and pass namespace; otherwise use the active space.",
inputSchema,
outputSchema: listDocumentsOutputSchema,
annotations: READ_ONLY_TOOL_ANNOTATIONS,
},
async (args) => {
try {
const effectiveTag = await deps.resolveContainerTag(args.containerTag)
const client = deps.getClient(effectiveTag)
const namespace = await deps.resolveNamespace(namespaceArg(args))
const client = deps.getClient(namespace)
const data = await client.listDocuments(
args.page ?? 1,
args.limit ?? 10,

View file

@ -1,5 +1,6 @@
import { z } from "zod"
import { optionalContainerTagSchema } from "../container-tag"
import { optionalNamespaceSchema } from "../namespace"
import { legacyNamespaceInput, namespaceArg } from "./compat"
import { formatMemoryEntriesList } from "../format"
import { READ_ONLY_TOOL_ANNOTATIONS } from "./annotations"
import {
@ -25,7 +26,8 @@ export function register(deps: ToolDeps) {
.optional()
.default(10)
.describe("Memory entries per page (default 10, max 50)"),
containerTag: optionalContainerTagSchema,
namespace: optionalNamespaceSchema,
...legacyNamespaceInput,
})
deps.server.registerTool(
@ -33,15 +35,15 @@ export function register(deps: ToolDeps) {
{
title: "List Memories",
description:
"List the latest extracted memory entries in one space, including stable memory IDs, version information, and source document IDs. This lists memories directly, not documents. When the user names a space, resolve it with list_spaces and pass containerTag; otherwise use the active space. Use search_memory instead for semantic recall.",
"List the latest extracted memory entries in one space, including stable memory IDs and version information. This lists memories directly, not documents. When the user names a space, resolve it with list_spaces and pass namespace; otherwise use the active space. Use search_memory instead for semantic recall.",
inputSchema,
outputSchema: listMemoriesOutputSchema,
annotations: READ_ONLY_TOOL_ANNOTATIONS,
},
async (args) => {
try {
const effectiveTag = await deps.resolveContainerTag(args.containerTag)
const client = deps.getClient(effectiveTag)
const namespace = await deps.resolveNamespace(namespaceArg(args))
const client = deps.getClient(namespace)
const data = await client.listMemoryEntries(
args.page ?? 1,
args.limit ?? 10,

View file

@ -0,0 +1,51 @@
import { z } from "zod"
import { listSpacesOutputSchema } from "../../shared/types"
import { READ_ONLY_TOOL_ANNOTATIONS } from "./annotations"
import { withLegacyNamespaces } from "./compat"
import { textContent, type ToolDeps } from "./types"
export function register(deps: ToolDeps) {
deps.server.registerTool(
"list_spaces",
{
description:
"List the spaces available to the user. Returns each space's key, description, document/memory counts, and last update. Use this first to resolve a named space before calling a space-aware tool, or when the user asks which space may contain something. The list is auto-filtered to spaces the user can access.",
inputSchema: z.object({}),
outputSchema: listSpacesOutputSchema,
annotations: READ_ONLY_TOOL_ANNOTATIONS,
},
async () => {
try {
const namespaces = await deps.getClient().listNamespaces()
const spaces = withLegacyNamespaces(
namespaces.map((entry) => ({
namespace: entry.namespace,
description: entry.description,
documentCount: entry.documentCount,
memoryCount: entry.memoryCount,
updatedAt: entry.updatedAt,
})),
)
if (spaces.length === 0) {
return {
content: [textContent("No spaces found.")],
structuredContent: { spaces, count: 0 },
}
}
const lines = spaces.map(
(space) =>
`- ${space.namespace} (${space.documentCount} docs, ${space.memoryCount} memories)`,
)
return {
content: [textContent(`Available spaces:\n${lines.join("\n")}`)],
structuredContent: { spaces, count: spaces.length },
}
} catch (error) {
return deps.errorResult(error)
}
},
)
}

View file

@ -1,13 +1,15 @@
import { z } from "zod"
import { graphViewSchema, type ViewMessage } from "../../shared/types"
import { appResultMeta, appToolMeta } from "../app-metadata"
import { optionalContainerTagSchema } from "../container-tag"
import { optionalNamespaceSchema } from "../namespace"
import { legacyNamespaceInput, namespaceArg, withLegacyView } from "./compat"
import { READ_ONLY_TOOL_ANNOTATIONS } from "./annotations"
import { textContent, type ToolDeps } from "./types"
export function register(deps: ToolDeps) {
const inputSchema = z.object({
containerTag: optionalContainerTagSchema,
namespace: optionalNamespaceSchema,
...legacyNamespaceInput,
})
deps.server.registerTool(
@ -15,7 +17,7 @@ export function register(deps: ToolDeps) {
{
title: "Memory Graph",
description:
"Render a space's memory graph directly as an interactive MCP App. This tool is the final visualization; do not create another graph, file, or artifact unless the user explicitly asks for one. If the user names a space, call list_spaces to resolve its key and pass it as containerTag. If the user does not name a space, call this tool directly and omit containerTag; the server uses the active space or account default. Do not open the space picker unless the user asks to change their active space.",
"Render a space's memory graph directly as an interactive MCP App. This tool is the final visualization; do not create another graph, file, or artifact unless the user explicitly asks for one. If the user names a space, call list_spaces to resolve its key and pass it as namespace. If the user does not name a space, call this tool directly and omit namespace; the server uses the active space or account default. Do not open the space picker unless the user asks to change their active space.",
inputSchema,
outputSchema: graphViewSchema,
annotations: READ_ONLY_TOOL_ANNOTATIONS,
@ -24,17 +26,17 @@ export function register(deps: ToolDeps) {
async (args) => {
try {
const viewId = crypto.randomUUID()
const effectiveTag = await deps.resolveContainerTag(args.containerTag)
const client = deps.getClient(effectiveTag)
const result = await client.getDocuments([effectiveTag], 1, 200)
const namespace = await deps.resolveNamespace(namespaceArg(args))
const client = deps.getClient(namespace)
const result = await client.getGraphDocuments(1, 200)
const memoryCount = result.documents.reduce(
(sum, document) => sum + document.memoryEntries.length,
0,
)
const sc: ViewMessage = {
const sc: ViewMessage = withLegacyView({
view: "graph",
viewId,
containerTag: effectiveTag,
namespace,
documents: result.documents,
totalCount: result.pagination.totalItems,
documentCount: result.documents.length,
@ -42,11 +44,11 @@ export function register(deps: ToolDeps) {
totalDocumentCount: result.pagination.totalItems,
truncated: result.documents.length < result.pagination.totalItems,
rendered: true,
}
})
return {
content: [
textContent(
`Rendered the interactive Memory Graph MCP App: ${result.documents.length} documents, ${memoryCount} memories. Space: ${effectiveTag}. Do not create a duplicate graph or artifact unless the user explicitly requests one.`,
`Rendered the interactive Memory Graph MCP App: ${result.documents.length} documents, ${memoryCount} memories. Space: ${namespace}. Do not create a duplicate graph or artifact unless the user explicitly requests one.`,
),
],
structuredContent: sc,

View file

@ -1,43 +1,17 @@
import { z } from "zod"
import { legacyNamespaceOutput } from "./compat"
import {
containerTagAccessSchema,
namespaceAccessSchema,
memoriesListSchema,
paginationSchema,
sessionScopeSchema,
} from "../../shared/types"
const documentStatusSchema = z.enum([
"unknown",
"queued",
"extracting",
"chunking",
"embedding",
"indexing",
"done",
"failed",
])
const documentTypeSchema = z.enum([
"text",
"pdf",
"tweet",
"google_doc",
"google_slide",
"google_sheet",
"image",
"video",
"audio",
"notion_doc",
"webpage",
"onedrive",
"github_markdown",
])
const documentSummarySchema = z.object({
id: z.string(),
title: z.string().nullable(),
type: documentTypeSchema,
status: documentStatusSchema,
type: z.string(),
status: z.string(),
createdAt: z.string(),
updatedAt: z.string(),
summary: z.string().nullable(),
@ -46,7 +20,8 @@ const documentSummarySchema = z.object({
export const addMemoryOutputSchema = z.object({
action: z.enum(["save", "forget"]),
success: z.boolean(),
containerTag: z.string(),
namespace: z.string(),
...legacyNamespaceOutput,
message: z.string(),
id: z.string().optional(),
status: z.string().optional(),
@ -55,14 +30,15 @@ export const addMemoryOutputSchema = z.object({
export type AddMemoryOutput = z.infer<typeof addMemoryOutputSchema>
export const getDocumentOutputSchema = z.object({
namespace: z.string(),
...legacyNamespaceOutput,
document: z.object({
id: z.string(),
title: z.string().nullable(),
type: documentTypeSchema,
status: documentStatusSchema,
type: z.string(),
status: z.string(),
createdAt: z.string(),
updatedAt: z.string(),
url: z.string().nullable(),
summary: z.string().nullable(),
content: z.string().nullable(),
contentTruncated: z.boolean(),
@ -78,15 +54,14 @@ export const listDocumentsOutputSchema = z.object({
export type ListDocumentsOutput = z.infer<typeof listDocumentsOutputSchema>
// Reuse the shared schema so the tool's output contract stays identical to what
// the client parses — the two can't drift.
export const listMemoriesOutputSchema = memoriesListSchema
export type ListMemoriesOutput = z.infer<typeof listMemoriesOutputSchema>
export const searchMemoryOutputSchema = z.object({
query: z.string(),
containerTag: z.string(),
namespace: z.string(),
...legacyNamespaceOutput,
profile: z
.object({
static: z.array(z.string()),
@ -108,7 +83,8 @@ export const searchMemoryOutputSchema = z.object({
export type SearchMemoryOutput = z.infer<typeof searchMemoryOutputSchema>
export const getProfileOutputSchema = z.object({
containerTag: z.string(),
namespace: z.string(),
...legacyNamespaceOutput,
profile: z.object({
static: z.array(z.string()),
dynamic: z.array(z.string()),
@ -124,7 +100,7 @@ export const whoAmIOutputSchema = z.object({
role: z.string(),
accessType: z.enum(["full", "restricted"]),
activeSpace: z.string().nullable(),
assignedSpaces: z.array(containerTagAccessSchema).nullable(),
assignedSpaces: z.array(namespaceAccessSchema).nullable(),
scope: sessionScopeSchema.optional(),
client: z
.object({

View file

@ -1,6 +1,8 @@
import { z } from "zod"
import { uploadPreparationSchema } from "../../shared/types"
import { appToolMeta } from "../app-metadata"
import { namespaceSchema } from "../namespace"
import { legacyNamespaceInput, namespaceArg } from "./compat"
import { ADDITIVE_MEMORY_TOOL_ANNOTATIONS } from "./annotations"
import { textContent, type ToolDeps } from "./types"
@ -9,14 +11,18 @@ export function register(deps: ToolDeps) {
"prepare-file-upload",
{
description: "Prepare a direct file upload",
inputSchema: z.object({}),
inputSchema: z.object({
namespace: namespaceSchema.optional(),
...legacyNamespaceInput,
}),
outputSchema: uploadPreparationSchema,
annotations: ADDITIVE_MEMORY_TOOL_ANNOTATIONS,
_meta: appToolMeta(["app"]),
},
async () => {
async (args) => {
try {
const preparation = await deps.createUploadSession()
const namespace = await deps.resolveNamespace(namespaceArg(args))
const preparation = await deps.createUploadSession(namespace)
return {
content: [textContent("Upload session prepared")],

View file

@ -1,7 +1,8 @@
import { z } from "zod"
import { saveSuccessViewSchema, type ViewMessage } from "../../shared/types"
import { appResultMeta, appToolMeta } from "../app-metadata"
import { containerTagSchema } from "../container-tag"
import { namespaceSchema } from "../namespace"
import { legacyNamespaceInput, namespaceArg, withLegacyView } from "./compat"
import { ADDITIVE_MEMORY_TOOL_ANNOTATIONS } from "./annotations"
import { textContent, type ToolDeps } from "./types"
@ -12,7 +13,8 @@ export function register(deps: ToolDeps) {
description: "Save content to memory",
inputSchema: z.object({
content: z.string().min(1),
containerTag: containerTagSchema,
namespace: namespaceSchema.optional(),
...legacyNamespaceInput,
viewId: z.string().uuid().optional(),
}),
outputSchema: saveSuccessViewSchema,
@ -21,15 +23,18 @@ export function register(deps: ToolDeps) {
},
async (args) => {
try {
const namespace = namespaceArg(args)
if (!namespace)
return deps.errorResult(new Error("namespace is required"))
const viewId = args.viewId ?? crypto.randomUUID()
const client = deps.getClient(args.containerTag)
const client = deps.getClient(namespace)
const result = await client.createMemory(args.content)
const sc: ViewMessage = {
const sc: ViewMessage = withLegacyView({
view: "save-success",
viewId,
id: result.id,
containerTag: args.containerTag,
}
namespace,
})
return {
content: [textContent(`Memory saved: ${result.id}`)],
structuredContent: sc,

View file

@ -1,6 +1,11 @@
import { z } from "zod"
import { getMemoryText } from "../client"
import { optionalContainerTagSchema } from "../container-tag"
import { optionalNamespaceSchema } from "../namespace"
import {
legacyNamespaceInput,
namespaceArg,
withLegacyNamespace,
} from "./compat"
import { READ_ONLY_TOOL_ANNOTATIONS } from "./annotations"
import {
searchMemoryOutputSchema,
@ -14,29 +19,29 @@ export function register(deps: ToolDeps) {
.string()
.max(1000, "Query exceeds maximum length")
.describe("The search query to find relevant memories"),
containerTag: optionalContainerTagSchema,
namespace: optionalNamespaceSchema,
...legacyNamespaceInput,
})
deps.server.registerTool(
"search_memory",
{
description:
"Search memories in one space with a natural-language query. Returns matching memories only — not the space profile. If you need who-the-user-is, preferences, or recent context after searching, call get_profile. When the user names a space, resolve it with list_spaces and pass containerTag; otherwise use the active space.",
"Search memories in one space with a natural-language query. Returns matching memories only — not the space profile. If you need who-the-user-is, preferences, or recent context after searching, call get_profile. When the user names a space, resolve it with list_spaces and pass namespace; otherwise use the active space.",
inputSchema,
outputSchema: searchMemoryOutputSchema,
annotations: READ_ONLY_TOOL_ANNOTATIONS,
},
async (args) => {
try {
const effectiveTag = await deps.resolveContainerTag(args.containerTag)
const client = deps.getClient(effectiveTag)
const namespace = await deps.resolveNamespace(namespaceArg(args))
const client = deps.getClient(namespace)
const searchResult = await client.search(args.query)
const results = searchResult.results.map((result) => ({
id: result.id,
text: getMemoryText(result),
similarity: result.similarity,
...(result.title ? { title: result.title } : {}),
}))
const parts: string[] = []
@ -51,13 +56,13 @@ export function register(deps: ToolDeps) {
parts.push("No matching memories found.")
}
const structuredContent: SearchMemoryOutput = {
const structuredContent: SearchMemoryOutput = withLegacyNamespace({
query: args.query,
containerTag: effectiveTag,
namespace,
results,
total: searchResult.total,
timing: searchResult.timing,
}
})
return {
content: [textContent(parts.join("\n"))],

View file

@ -1,8 +1,9 @@
import { z } from "zod"
import { pickerViewSchema, type ViewMessage } from "../../shared/types"
import { appResultMeta, appToolMeta } from "../app-metadata"
import { effectiveContainerTagAccess } from "../auth/rbac"
import { effectiveNamespaceAccess } from "../auth/rbac"
import { READ_ONLY_TOOL_ANNOTATIONS } from "./annotations"
import { withLegacyView } from "./compat"
import { textContent, type ToolDeps } from "./types"
export function register(deps: ToolDeps) {
@ -11,7 +12,7 @@ export function register(deps: ToolDeps) {
{
title: "Select Space",
description:
"Open an interactive picker to choose or change the active Supermemory space used for future actions. Use this only when the user asks to switch, select, or change their active or default space. Do not use it merely because the user names a space for a search, list, graph, save, or upload; resolve that space with list_spaces and pass containerTag to the relevant tool instead.",
"Open an interactive picker to choose or change the active Supermemory space used for future actions. Use this only when the user asks to switch, select, or change their active or default space. Do not use it merely because the user names a space for a search, list, graph, save, or upload; resolve that space with list_spaces and pass namespace to the relevant tool instead.",
inputSchema: z.object({}),
outputSchema: pickerViewSchema,
_meta: appToolMeta(),
@ -21,28 +22,28 @@ export function register(deps: ToolDeps) {
try {
const viewId = crypto.randomUUID()
const client = deps.getClient()
const [tags, session, activeTag] = await Promise.all([
client.listContainerTags(),
const [namespaces, session, activeNamespace] = await Promise.all([
client.listNamespaces(),
deps.getSession(),
deps.getActiveContainerTag(),
deps.getActiveNamespace(),
])
const assignedTags = effectiveContainerTagAccess(
tags.map((tag) => tag.containerTag),
const assignedNamespaces = effectiveNamespaceAccess(
namespaces.map((entry) => entry.namespace),
session,
)
const sc: ViewMessage = {
const sc: ViewMessage = withLegacyView({
view: "picker",
viewId,
containerTags: tags,
activeTag,
assignedTags,
}
namespaces,
activeNamespace,
assignedNamespaces,
})
return {
content: [
textContent(
`${tags.length} spaces available. Select one to set your active context.`,
`${namespaces.length} spaces available. Select one to set your active context.`,
),
],
structuredContent: sc,

View file

@ -1,7 +1,8 @@
import { z } from "zod"
import { confirmationViewSchema, type ViewMessage } from "../../shared/types"
import { appResultMeta, appToolMeta } from "../app-metadata"
import { containerTagSchema } from "../container-tag"
import { namespaceSchema } from "../namespace"
import { legacyNamespaceInput, namespaceArg, withLegacyView } from "./compat"
import { SETTINGS_TOOL_ANNOTATIONS } from "./annotations"
import { textContent, type ToolDeps } from "./types"
@ -11,7 +12,8 @@ export function register(deps: ToolDeps) {
{
description: "Set the active Supermemory space for this account",
inputSchema: z.object({
containerTag: containerTagSchema,
namespace: namespaceSchema.optional(),
...legacyNamespaceInput,
viewId: z.string().uuid().optional(),
}),
outputSchema: confirmationViewSchema,
@ -19,23 +21,24 @@ export function register(deps: ToolDeps) {
annotations: SETTINGS_TOOL_ANNOTATIONS,
},
async (args) => {
const { containerTag } = args
const namespace = namespaceArg(args)
if (!namespace)
return deps.errorResult(new Error("namespace is required"))
try {
const viewId = args.viewId ?? crypto.randomUUID()
const tags = await deps.getClient().listContainerTags()
if (!tags.some((tag) => tag.containerTag === containerTag)) {
if (!(await deps.getClient().getNamespace(namespace))) {
return deps.errorResult(
new Error(`No access to container tag '${containerTag}'.`),
new Error(`No access to namespace '${namespace}'.`),
)
}
await deps.setActiveContainerTag(containerTag)
const sc: ViewMessage = {
await deps.setActiveNamespace(namespace)
const sc: ViewMessage = withLegacyView({
view: "confirmation",
viewId,
containerTag,
}
namespace,
})
return {
content: [textContent(`Active space set to ${containerTag}`)],
content: [textContent(`Active space set to ${namespace}`)],
structuredContent: sc,
_meta: appResultMeta(viewId),
}

View file

@ -14,17 +14,16 @@ export interface PreparedUpload {
expiresAt: number
}
// Dependencies passed to every tool's register() function.
// Keep this surface small — tools should read this rather than reach into the agent.
// Keep this surface small: tools read deps rather than reach into the agent.
export interface ToolDeps {
server: Pick<McpServer, "registerTool">
actor: ActorContext
getClient: (containerTag?: string) => SupermemoryClient
getClient: (namespace?: string) => SupermemoryClient
getSession: () => Promise<SessionInfo>
resolveContainerTag: (explicit?: string) => Promise<string>
getActiveContainerTag: () => Promise<string | undefined>
setActiveContainerTag: (containerTag: string) => Promise<void>
createUploadSession: () => Promise<PreparedUpload>
resolveNamespace: (explicit?: string) => Promise<string>
getActiveNamespace: () => Promise<string | undefined>
setActiveNamespace: (namespace: string) => Promise<void>
createUploadSession: (namespace: string) => Promise<PreparedUpload>
getClientInfo: (
context: ServerContext,
) => { name: string; version?: string } | null

View file

@ -1,8 +1,9 @@
import { z } from "zod"
import { uploadViewSchema, type ViewMessage } from "../../shared/types"
import { appResultMeta, appToolMeta } from "../app-metadata"
import { effectiveContainerTagAccess } from "../auth/rbac"
import { effectiveNamespaceAccess } from "../auth/rbac"
import { READ_ONLY_TOOL_ANNOTATIONS } from "./annotations"
import { withLegacyView } from "./compat"
import { textContent, type ToolDeps } from "./types"
export function register(deps: ToolDeps) {
@ -20,24 +21,24 @@ export function register(deps: ToolDeps) {
async () => {
try {
const viewId = crypto.randomUUID()
const [activeTag, tags, session] = await Promise.all([
deps.getActiveContainerTag(),
deps.getClient().listContainerTags(),
const [activeNamespace, namespaces, session] = await Promise.all([
deps.getActiveNamespace(),
deps.getClient().listNamespaces(),
deps.getSession(),
])
const writableTags = effectiveContainerTagAccess(
tags.map((tag) => tag.containerTag),
const writableNamespaces = effectiveNamespaceAccess(
namespaces.map((entry) => entry.namespace),
session,
)
.filter((access) => access.permission === "write")
.map((access) => access.containerTag)
.map((access) => access.namespace)
const sc: ViewMessage = {
const sc: ViewMessage = withLegacyView({
view: "upload",
viewId,
activeTag,
writableTags,
}
activeNamespace,
writableNamespaces,
})
return {
content: [textContent("Opening file upload form...")],

View file

@ -1,5 +1,6 @@
import { z } from "zod"
import { READ_ONLY_TOOL_ANNOTATIONS } from "./annotations"
import { withLegacyNamespaces } from "./compat"
import { whoAmIOutputSchema, type WhoAmIOutput } from "./output-schemas"
import { textContent, type ToolDeps } from "./types"
@ -15,9 +16,9 @@ export function register(deps: ToolDeps) {
},
async (_args, context) => {
try {
const [session, activeTag] = await Promise.all([
const [session, activeNamespace] = await Promise.all([
deps.getSession(),
deps.getActiveContainerTag(),
deps.getActiveNamespace(),
])
const client = deps.getClientInfo(context)
const structuredContent: WhoAmIOutput = {
@ -26,10 +27,10 @@ export function register(deps: ToolDeps) {
...(session.user.name ? { name: session.user.name } : {}),
role: session.role ?? "unknown",
accessType: session.accessType ?? "full",
activeSpace: activeTag ?? null,
activeSpace: activeNamespace ?? null,
assignedSpaces:
session.accessType === "restricted"
? (session.containerTags ?? null)
session.accessType === "restricted" && session.namespaces
? withLegacyNamespaces(session.namespaces)
: null,
...(session.scope ? { scope: session.scope } : {}),
...(client ? { client } : {}),

View file

@ -3,12 +3,21 @@ import { z } from "zod"
// Shared types — imported by both server tools and widget views.
// Single source of truth for the server↔widget contract.
export const containerTagAccessSchema = z.object({
containerTag: z.string(),
export const namespaceAccessSchema = z.object({
namespace: z.string(),
containerTag: z.string().optional(),
permission: z.enum(["read", "write"]),
})
export type ContainerTagAccess = z.infer<typeof containerTagAccessSchema>
export type NamespaceAccess = z.infer<typeof namespaceAccessSchema>
// /v3/session has no v5 replacement and still sends container-tag field names.
const sessionNamespaceAccessSchema = z
.object({ containerTag: z.string(), permission: z.enum(["read", "write"]) })
.transform(({ containerTag, permission }) => ({
namespace: containerTag,
permission,
}))
export const sessionScopeSchema = z.looseObject({
type: z.enum(["full", "scoped"]),
@ -21,48 +30,51 @@ export const sessionScopeSchema = z.looseObject({
export type SessionScope = z.infer<typeof sessionScopeSchema>
export const sessionInfoSchema = z.looseObject({
user: z.looseObject({
id: z.string().min(1),
email: z.string().optional(),
name: z.string().optional(),
}),
org: z.looseObject({ id: z.string().min(1) }).optional(),
role: z.string().optional(),
accessType: z.enum(["full", "restricted"]).optional(),
containerTags: z.array(containerTagAccessSchema).nullable().optional(),
scope: sessionScopeSchema.optional(),
})
export const sessionInfoSchema = z
.looseObject({
user: z.looseObject({
id: z.string().min(1),
email: z.string().optional(),
name: z.string().optional(),
}),
org: z.looseObject({ id: z.string().min(1) }).optional(),
role: z.string().optional(),
accessType: z.enum(["full", "restricted"]).optional(),
containerTags: z.array(sessionNamespaceAccessSchema).nullable().optional(),
scope: sessionScopeSchema.optional(),
})
.transform(
({
containerTags,
...session
}): typeof session & { namespaces?: NamespaceAccess[] | null } => ({
...session,
namespaces: containerTags,
}),
)
export type SessionInfo = z.infer<typeof sessionInfoSchema>
export type SessionInfo = z.output<typeof sessionInfoSchema>
export const containerTagSchema = z.looseObject({
export const namespaceInfoSchema = z.object({
id: z.string(),
name: z.string(),
containerTag: z.string(),
namespace: z.string(),
containerTag: z.string().optional(),
description: z.string().nullish(),
visibility: z.string().nullish(),
documentCount: z.number().int().nonnegative(),
memoryCount: z.number().int().nonnegative(),
createdAt: z.string(),
updatedAt: z.string(),
isExperimental: z.boolean(),
emoji: z.string().nullish(),
isNova: z.boolean(),
documentCount: z.number().int().nonnegative(),
memoryCount: z.number().int().nonnegative(),
lastActivityAt: z.string().nullish(),
})
export type ContainerTag = z.infer<typeof containerTagSchema>
export type NamespaceInfo = z.infer<typeof namespaceInfoSchema>
export const spaceSummarySchema = z.object({
name: z.string(),
containerTag: z.string(),
namespace: z.string(),
containerTag: z.string().optional(),
description: z.string().nullish(),
visibility: z.string().nullish(),
emoji: z.string().nullish(),
documentCount: z.number().int().nonnegative(),
memoryCount: z.number().int().nonnegative(),
lastActivityAt: z.string().nullish(),
updatedAt: z.string(),
})
export const listSpacesOutputSchema = z.object({
@ -117,11 +129,7 @@ export const documentsApiResponseSchema = z.object({
export type DocumentsApiResponse = z.infer<typeof documentsApiResponseSchema>
// Extracted memory entries from /v4/memories/list. Single source of truth for
// both the client parser and the listMemories tool output schema, so the two
// can't drift (a mismatch previously produced Ajv "must NOT have additional
// properties"). z.object strips unknown API fields on parse, keeping parsed data
// matched to the strict MCP output contract while tolerating new API fields.
// Shared by the client and the list_memories output schema so the two can't drift.
export const memoryEntryHistorySchema = z.object({
id: z.string(),
memory: z.string(),
@ -168,37 +176,46 @@ const viewIdSchema = z.string().uuid().optional()
export const pickerViewSchema = z.object({
view: z.literal("picker"),
viewId: viewIdSchema,
containerTags: z.array(containerTagSchema),
namespaces: z.array(namespaceInfoSchema),
activeNamespace: z.string().nullish(),
assignedNamespaces: z.array(namespaceAccessSchema).nullable().optional(),
containerTags: z.array(namespaceInfoSchema).optional(),
activeTag: z.string().nullish(),
assignedTags: z.array(containerTagAccessSchema).nullable().optional(),
assignedTags: z.array(namespaceAccessSchema).nullable().optional(),
})
export const confirmationViewSchema = z.object({
view: z.literal("confirmation"),
viewId: viewIdSchema,
containerTag: z.string(),
namespace: z.string(),
containerTag: z.string().optional(),
})
export const saveViewSchema = z.object({
view: z.literal("save"),
viewId: viewIdSchema,
activeTag: z.string().nullish(),
writableTags: z.array(z.string()),
activeNamespace: z.string().nullish(),
writableNamespaces: z.array(z.string()),
prefill: z.string().optional(),
activeTag: z.string().nullish(),
writableTags: z.array(z.string()).optional(),
})
export const saveSuccessViewSchema = z.object({
view: z.literal("save-success"),
viewId: viewIdSchema,
id: z.string(),
containerTag: z.string(),
namespace: z.string(),
containerTag: z.string().optional(),
})
export const uploadViewSchema = z.object({
view: z.literal("upload"),
viewId: viewIdSchema,
activeNamespace: z.string().nullish(),
writableNamespaces: z.array(z.string()),
activeTag: z.string().nullish(),
writableTags: z.array(z.string()),
writableTags: z.array(z.string()).optional(),
})
export const uploadSuccessViewSchema = z.object({
@ -206,7 +223,8 @@ export const uploadSuccessViewSchema = z.object({
viewId: viewIdSchema,
id: z.string(),
fileName: z.string(),
containerTag: z.string(),
namespace: z.string(),
containerTag: z.string().optional(),
})
export const uploadPreparationSchema = z.object({
@ -223,6 +241,7 @@ export const uploadResponseSchema = z.object({
export const graphViewSchema = z.object({
view: z.literal("graph"),
viewId: viewIdSchema,
namespace: z.string().optional(),
containerTag: z.string().optional(),
documents: z.array(documentWithMemoriesSchema),
totalCount: z.number().int().nonnegative(),

View file

@ -90,9 +90,9 @@ function renderView(
case "picker":
return (
<Picker
activeTag={msg.activeTag}
assignedTags={msg.assignedTags}
containerTags={msg.containerTags}
activeNamespace={msg.activeNamespace}
assignedNamespaces={msg.assignedNamespaces}
namespaces={msg.namespaces}
onAdvance={setView}
onError={setError}
viewId={msg.viewId}
@ -101,36 +101,36 @@ function renderView(
case "save":
return (
<Save
activeTag={msg.activeTag}
activeNamespace={msg.activeNamespace}
onAdvance={setView}
onError={setError}
prefill={msg.prefill}
viewId={msg.viewId}
writableTags={msg.writableTags}
writableNamespaces={msg.writableNamespaces}
/>
)
case "upload":
return (
<Upload
activeTag={msg.activeTag}
activeNamespace={msg.activeNamespace}
onAdvance={setView}
onError={setError}
viewId={msg.viewId}
writableTags={msg.writableTags}
writableNamespaces={msg.writableNamespaces}
/>
)
case "graph":
return <Graph documents={msg.documents} totalCount={msg.totalCount} />
case "confirmation":
return <Confirmation containerTag={msg.containerTag} />
return <Confirmation namespace={msg.namespace} />
case "save-success":
return <Success containerTag={msg.containerTag} kind="save" />
return <Success kind="save" namespace={msg.namespace} />
case "upload-success":
return (
<Success
containerTag={msg.containerTag}
fileName={msg.fileName}
kind="upload"
namespace={msg.namespace}
/>
)
default: {

View file

@ -1,19 +1,19 @@
import type { ContainerTag, ContainerTagAccess } from "../../shared/types"
import type { NamespaceAccess, NamespaceInfo } from "../../shared/types"
import { cn } from "../design/lib/cn"
import { formatTagLabel } from "../lib/formatTag"
import { formatNamespaceLabel } from "../lib/formatNamespace"
import { PermissionBadge } from "./PermissionBadge"
interface Props {
containerTag: ContainerTag
namespace: NamespaceInfo
active: boolean
access?: ContainerTagAccess
onClick: (containerTag: string) => void
access?: NamespaceAccess
onClick: (namespace: string) => void
}
export function SpaceCard({ containerTag, active, access, onClick }: Props) {
const name = containerTag.name || formatTagLabel(containerTag.containerTag)
const docs = containerTag.documentCount
const mems = containerTag.memoryCount
export function SpaceCard({ namespace, active, access, onClick }: Props) {
const name = formatNamespaceLabel(namespace.namespace)
const docs = namespace.documentCount
const mems = namespace.memoryCount
const meta =
docs > 0 || mems > 0
? `${docs} doc${docs === 1 ? "" : "s"} · ${mems} ${mems === 1 ? "memory" : "memories"}`
@ -23,7 +23,7 @@ export function SpaceCard({ containerTag, active, access, onClick }: Props) {
<button
className="space-card"
data-active={active}
onClick={() => onClick(containerTag.containerTag)}
onClick={() => onClick(namespace.namespace)}
type="button"
>
<span className="space-card-inner">

View file

@ -1,11 +1,11 @@
import { formatTagLabel } from "../lib/formatTag"
import { formatNamespaceLabel } from "../lib/formatNamespace"
// A calm space pill: a small accent dot + the space name on a neutral surface.
export function SpaceChip({ containerTag }: { containerTag: string }) {
export function SpaceChip({ namespace }: { namespace: string }) {
return (
<span className="inline-flex items-center gap-1.5 rounded-full bg-bg-muted px-2.5 py-1 text-(length:--text-xs) font-medium text-text-primary">
<span aria-hidden className="size-1.5 shrink-0 rounded-full bg-accent" />
{formatTagLabel(containerTag)}
{formatNamespaceLabel(namespace)}
</span>
)
}

View file

@ -0,0 +1,9 @@
// "sm_project_eng_rfcs" → "Eng Rfcs"
export function formatNamespaceLabel(raw: string): string {
const slug = raw.replace(/^sm_project_/i, "").replace(/^sm_/i, "")
return slug
.split("_")
.map((w) => w.charAt(0).toUpperCase() + w.slice(1))
.join(" ")
}

View file

@ -1,15 +0,0 @@
/**
* Turns a raw container-tag identifier into a human-friendly label.
*
* "sm_project_marketing" → "Marketing"
* "sm_project_eng_rfcs" → "Eng Rfcs"
* "my_custom_space" → "My Custom Space"
*/
export function formatTagLabel(raw: string): string {
const slug = raw.replace(/^sm_project_/i, "").replace(/^sm_/i, "")
return slug
.split("_")
.map((w) => w.charAt(0).toUpperCase() + w.slice(1))
.join(" ")
}

View file

@ -41,11 +41,11 @@ function getStorage(): Storage | undefined {
function modelContentForView(view: ViewMessage): string {
switch (view.view) {
case "confirmation":
return `Supermemory active space is now "${view.containerTag}".`
return `Supermemory active space is now "${view.namespace}".`
case "save-success":
return `A memory was saved to Supermemory space "${view.containerTag}" with memory ID "${view.id}".`
return `A memory was saved to Supermemory space "${view.namespace}" with memory ID "${view.id}".`
case "upload-success":
return `"${view.fileName}" was uploaded to Supermemory space "${view.containerTag}" with document ID "${view.id}".`
return `"${view.fileName}" was uploaded to Supermemory space "${view.namespace}" with document ID "${view.id}".`
default:
return "Supermemory widget state updated."
}

View file

@ -24,11 +24,12 @@ import { Save } from "../views/Save"
import { Success } from "../views/Success"
import { Upload } from "../views/Upload"
import {
mockAssignedTags,
mockContainerTags,
mockAssignedNamespaces,
mockNamespaces,
mockDocuments,
mockWritableTags,
mockWritableNamespaces,
} from "./mocks"
import { formatNamespaceLabel } from "../lib/formatNamespace"
type Theme = "light" | "dark"
type Width = "narrow" | "wide" | "cursor"
@ -289,24 +290,24 @@ export function Studio() {
<div className="flex flex-wrap gap-(--space-4)">
<div className="w-64">
<SpaceCard
access={mockAssignedTags[0]}
access={mockAssignedNamespaces[0]}
active={false}
containerTag={mockContainerTags[0]}
namespace={mockNamespaces[0]}
onClick={() => {}}
/>
</div>
<div className="w-64">
<SpaceCard
access={mockAssignedTags[1]}
access={mockAssignedNamespaces[1]}
active
containerTag={mockContainerTags[1]}
namespace={mockNamespaces[1]}
onClick={() => {}}
/>
</div>
<div className="w-64">
<SpaceCard
active={false}
containerTag={mockContainerTags[3]}
namespace={mockNamespaces[3]}
onClick={() => {}}
/>
</div>
@ -336,10 +337,10 @@ export function Studio() {
>
<SpaceSelect
onValueChange={setSelectValue}
options={mockContainerTags.map((t) => ({
value: t.containerTag,
label: t.name,
description: t.containerTag,
options={mockNamespaces.map((t) => ({
value: t.namespace,
label: formatNamespaceLabel(t.namespace),
description: t.namespace,
}))}
value={selectValue}
/>
@ -356,9 +357,9 @@ export function Studio() {
<Frame label="Picker" width={frameWidth}>
<WidgetShell>
<Picker
activeTag="sm_project_marketing"
assignedTags={mockAssignedTags}
containerTags={mockContainerTags}
activeNamespace="sm_project_marketing"
assignedNamespaces={mockAssignedNamespaces}
namespaces={mockNamespaces}
onAdvance={pickerStub.onAdvance}
onError={pickerStub.onError}
/>
@ -368,11 +369,11 @@ export function Studio() {
<Frame label="Save" width={frameWidth}>
<WidgetShell>
<Save
activeTag="sm_project_marketing"
activeNamespace="sm_project_marketing"
onAdvance={saveStub.onAdvance}
onError={saveStub.onError}
prefill="The Q3 launch will target fintech enterprise buyers."
writableTags={mockWritableTags}
writableNamespaces={mockWritableNamespaces}
/>
</WidgetShell>
</Frame>
@ -380,30 +381,30 @@ export function Studio() {
<Frame label="Upload" width={frameWidth}>
<WidgetShell>
<Upload
activeTag="sm_project_marketing"
activeNamespace="sm_project_marketing"
onAdvance={uploadStub.onAdvance}
onError={uploadStub.onError}
writableTags={mockWritableTags}
writableNamespaces={mockWritableNamespaces}
/>
</WidgetShell>
</Frame>
<Frame label="Confirmation" width={frameWidth}>
<WidgetShell>
<Confirmation containerTag="sm_project_marketing" />
<Confirmation namespace="sm_project_marketing" />
</WidgetShell>
</Frame>
<Frame label="Success (save)" width={frameWidth}>
<WidgetShell>
<Success containerTag="sm_project_marketing" kind="save" />
<Success namespace="sm_project_marketing" kind="save" />
</WidgetShell>
</Frame>
<Frame label="Success (upload)" width={frameWidth}>
<WidgetShell>
<Success
containerTag="sm_project_marketing"
namespace="sm_project_marketing"
fileName="q3-brief.pdf"
kind="upload"
/>
@ -412,7 +413,7 @@ export function Studio() {
<Frame label="Error" width={frameWidth}>
<WidgetShell>
<ErrorView message="No write access to container tag 'sm_project_eng_rfcs'." />
<ErrorView message="No write access to namespace 'sm_project_eng_rfcs'." />
</WidgetShell>
</Frame>

View file

@ -1,73 +1,55 @@
import type {
ContainerTag,
ContainerTagAccess,
DocumentWithMemories,
NamespaceAccess,
NamespaceInfo,
} from "../../shared/types"
// Mock data for the Studio gallery. Mirrors the shapes the server returns
// so views render exactly as they would in Claude Desktop.
export const mockContainerTags: ContainerTag[] = [
export const mockNamespaces: NamespaceInfo[] = [
{
id: "ct_1",
name: "Marketing",
containerTag: "sm_project_marketing",
id: "ns_1",
namespace: "sm_project_marketing",
description: "Positioning, launches, and campaign notes.",
createdAt: "2026-01-02T10:00:00Z",
updatedAt: "2026-05-30T14:20:00Z",
isExperimental: false,
emoji: "📣",
isNova: true,
documentCount: 42,
memoryCount: 318,
lastActivityAt: "2026-05-30T14:20:00Z",
},
{
id: "ct_2",
name: "Engineering RFCs",
containerTag: "sm_project_eng_rfcs",
id: "ns_2",
namespace: "sm_project_eng_rfcs",
createdAt: "2026-01-04T10:00:00Z",
updatedAt: "2026-05-29T09:00:00Z",
isExperimental: false,
emoji: "🛠️",
isNova: true,
documentCount: 17,
memoryCount: 96,
lastActivityAt: "2026-05-29T09:00:00Z",
},
{
id: "ct_3",
name: "Design System",
containerTag: "sm_project_design",
id: "ns_3",
namespace: "sm_project_design",
createdAt: "2026-02-01T10:00:00Z",
updatedAt: "2026-05-12T16:40:00Z",
isExperimental: false,
isNova: false,
documentCount: 8,
memoryCount: 1,
lastActivityAt: "2026-05-12T16:40:00Z",
},
{
id: "ct_4",
name: "Onboarding",
containerTag: "sm_project_onboarding",
id: "ns_4",
namespace: "sm_project_onboarding",
createdAt: "2026-03-01T10:00:00Z",
updatedAt: "2026-03-01T10:00:00Z",
isExperimental: true,
emoji: "🚀",
isNova: false,
documentCount: 0,
memoryCount: 0,
lastActivityAt: null,
},
]
export const mockAssignedTags: ContainerTagAccess[] = [
{ containerTag: "sm_project_marketing", permission: "write" },
{ containerTag: "sm_project_eng_rfcs", permission: "read" },
{ containerTag: "sm_project_design", permission: "write" },
export const mockAssignedNamespaces: NamespaceAccess[] = [
{ namespace: "sm_project_marketing", permission: "write" },
{ namespace: "sm_project_eng_rfcs", permission: "read" },
{ namespace: "sm_project_design", permission: "write" },
]
export const mockWritableTags: string[] = [
export const mockWritableNamespaces: string[] = [
"sm_project_marketing",
"sm_project_design",
]

View file

@ -3,10 +3,10 @@ import { Stack } from "../design/ui"
import { Check } from "../lib/icons"
interface Props {
containerTag: string
namespace: string
}
export function Confirmation({ containerTag }: Props) {
export function Confirmation({ namespace }: Props) {
return (
<Stack
align="center"
@ -20,7 +20,7 @@ export function Confirmation({ containerTag }: Props) {
<div className="text-(length:--text-sm) font-semibold text-text-primary">
Active space set
</div>
<SpaceChip containerTag={containerTag} />
<SpaceChip namespace={namespace} />
</Stack>
<p className="max-w-xs text-(length:--text-xs) leading-relaxed text-text-muted">
Saves and recalls will use this space until you change it.

View file

@ -1,20 +1,20 @@
import { useMemo, useState } from "react"
import {
type ContainerTag,
type ContainerTagAccess,
type NamespaceAccess,
type NamespaceInfo,
viewMessageSchema,
type ViewMessage,
} from "../../shared/types"
import { SpaceCard } from "../components/SpaceCard"
import { Input, PageHeader } from "../design/ui"
import { useApp } from "../hooks/useApp"
import { formatTagLabel } from "../lib/formatTag"
import { formatNamespaceLabel } from "../lib/formatNamespace"
import { Package, Search } from "../lib/icons"
interface Props {
containerTags: ContainerTag[]
activeTag?: string | null
assignedTags?: ContainerTagAccess[] | null
namespaces: NamespaceInfo[]
activeNamespace?: string | null
assignedNamespaces?: NamespaceAccess[] | null
onAdvance: (msg: ViewMessage) => void
onError: (message: string) => void
viewId?: string
@ -24,9 +24,9 @@ interface Props {
const SEARCH_THRESHOLD = 8
export function Picker({
containerTags,
activeTag,
assignedTags,
namespaces,
activeNamespace,
assignedNamespaces,
onAdvance,
onError,
viewId,
@ -36,21 +36,21 @@ export function Picker({
const [query, setQuery] = useState("")
const filtered = useMemo(() => {
if (!query.trim()) return containerTags
if (!query.trim()) return namespaces
const q = query.trim().toLowerCase()
return containerTags.filter(
(t) =>
t.name.toLowerCase().includes(q) ||
t.containerTag.toLowerCase().includes(q),
return namespaces.filter(
(entry) =>
formatNamespaceLabel(entry.namespace).toLowerCase().includes(q) ||
entry.namespace.toLowerCase().includes(q),
)
}, [containerTags, query])
}, [namespaces, query])
const handleSelect = async (containerTag: string) => {
setPending(containerTag)
const handleSelect = async (namespace: string) => {
setPending(namespace)
const result = await callTool(
"set-active-tag",
{
containerTag,
namespace,
viewId,
},
viewMessageSchema,
@ -62,18 +62,18 @@ export function Picker({
}
onAdvance(result.data)
await handoffToModel({
context: `Supermemory space selection changed. Active space: "${containerTag}". Use it for future Supermemory actions until another space is selected.`,
message: `I selected "${containerTag}" as my active Supermemory space. Use this space for future Supermemory actions until I select another one.`,
context: `Supermemory space selection changed. Active space: "${namespace}". Use it for future Supermemory actions until another space is selected.`,
message: `I selected "${namespace}" as my active Supermemory space. Use this space for future Supermemory actions until I select another one.`,
structuredContent: {
supermemory: {
action: "space-selected",
activeSpace: containerTag,
activeSpace: namespace,
},
},
})
}
const count = containerTags.length
const count = namespaces.length
const description =
count === 0
? "Create a space in Supermemory to get started."
@ -116,16 +116,16 @@ export function Picker({
</div>
) : (
<div className="space-picker-grid">
{filtered.map((tag) => {
const access = assignedTags?.find(
(t) => t.containerTag === tag.containerTag,
{filtered.map((entry) => {
const access = assignedNamespaces?.find(
(a) => a.namespace === entry.namespace,
)
return (
<SpaceCard
access={access}
active={activeTag === tag.containerTag}
containerTag={tag}
key={tag.id || tag.containerTag}
active={activeNamespace === entry.namespace}
key={entry.id || entry.namespace}
namespace={entry}
onClick={handleSelect}
/>
)
@ -137,7 +137,7 @@ export function Picker({
{pending ? (
<p className="text-(length:--text-xs) text-text-muted">
Setting space to {formatTagLabel(pending)}…
Setting space to {formatNamespaceLabel(pending)}…
</p>
) : null}
</div>

View file

@ -10,11 +10,11 @@ import {
SpaceSelect,
} from "../design/ui"
import { useApp } from "../hooks/useApp"
import { formatTagLabel } from "../lib/formatTag"
import { formatNamespaceLabel } from "../lib/formatNamespace"
interface Props {
activeTag?: string | null
writableTags: string[]
activeNamespace?: string | null
writableNamespaces: string[]
prefill?: string
onAdvance: (msg: ViewMessage) => void
onError: (message: string) => void
@ -22,8 +22,8 @@ interface Props {
}
export function Save({
activeTag,
writableTags,
activeNamespace,
writableNamespaces,
prefill,
onAdvance,
onError,
@ -31,38 +31,38 @@ export function Save({
}: Props) {
const { callTool, handoffToModel } = useApp()
const [content, setContent] = useState(prefill ?? "")
const [selectedTag, setSelectedTag] = useState<string | null>(
activeTag ?? writableTags[0] ?? null,
const [selectedNamespace, setSelectedNamespace] = useState<string | null>(
activeNamespace ?? writableNamespaces[0] ?? null,
)
const [saving, setSaving] = useState(false)
useEffect(() => {
if (!selectedTag && writableTags.length > 0) {
setSelectedTag(writableTags[0])
if (!selectedNamespace && writableNamespaces.length > 0) {
setSelectedNamespace(writableNamespaces[0])
}
}, [selectedTag, writableTags])
}, [selectedNamespace, writableNamespaces])
const options = useMemo(
() =>
writableTags.map((tag) => ({
value: tag,
label: formatTagLabel(tag),
description: tag,
writableNamespaces.map((namespace) => ({
value: namespace,
label: formatNamespaceLabel(namespace),
description: namespace,
})),
[writableTags],
[writableNamespaces],
)
const trimmed = content.trim()
const canSave = trimmed.length > 0 && !!selectedTag && !saving
const canSave = trimmed.length > 0 && !!selectedNamespace && !saving
const handleSave = async () => {
if (!canSave || !selectedTag) return
if (!canSave || !selectedNamespace) return
setSaving(true)
const result = await callTool(
"save-memory",
{
content: trimmed,
containerTag: selectedTag,
namespace: selectedNamespace,
viewId,
},
viewMessageSchema,
@ -76,12 +76,12 @@ export function Save({
result.data.view === "save-success" ? result.data.id : undefined
onAdvance(result.data)
await handoffToModel({
context: `Supermemory widget action completed. A memory was saved to space "${selectedTag}"${memoryId ? ` with memory ID "${memoryId}"` : ""}. Saved content:\n\n${trimmed}\n\nIt is already saved; do not save it again.`,
message: `I used the Supermemory widget to save a memory to space "${selectedTag}"${memoryId ? ` (memory ID: ${memoryId})` : ""}. The memory is already saved; do not save it again.`,
context: `Supermemory widget action completed. A memory was saved to space "${selectedNamespace}"${memoryId ? ` with memory ID "${memoryId}"` : ""}. Saved content:\n\n${trimmed}\n\nIt is already saved; do not save it again.`,
message: `I used the Supermemory widget to save a memory to space "${selectedNamespace}"${memoryId ? ` (memory ID: ${memoryId})` : ""}. The memory is already saved; do not save it again.`,
structuredContent: {
supermemory: {
action: "memory-saved",
activeSpace: selectedTag,
activeSpace: selectedNamespace,
memoryId,
content: trimmed,
},
@ -107,12 +107,12 @@ export function Save({
/>
</Field>
{writableTags.length > 0 ? (
{writableNamespaces.length > 0 ? (
<Field label="Space">
<SpaceSelect
onValueChange={setSelectedTag}
onValueChange={setSelectedNamespace}
options={options}
value={selectedTag}
value={selectedNamespace}
/>
</Field>
) : null}

View file

@ -4,13 +4,13 @@ import { Check } from "../lib/icons"
interface SaveProps {
kind: "save"
containerTag: string
namespace: string
}
interface UploadProps {
kind: "upload"
fileName: string
containerTag: string
namespace: string
}
type Props = SaveProps | UploadProps
@ -30,7 +30,7 @@ export function Success(props: Props) {
<div className="text-(length:--text-sm) font-semibold text-text-primary">
{isUpload ? `Uploaded ${props.fileName}` : "Memory saved"}
</div>
<SpaceChip containerTag={props.containerTag} />
<SpaceChip namespace={props.namespace} />
</Stack>
</Stack>
)

View file

@ -14,12 +14,12 @@ import {
SpaceSelect,
} from "../design/ui"
import { useApp } from "../hooks/useApp"
import { formatTagLabel } from "../lib/formatTag"
import { formatNamespaceLabel } from "../lib/formatNamespace"
import { FileText, X } from "../lib/icons"
interface Props {
activeTag?: string | null
writableTags: string[]
activeNamespace?: string | null
writableNamespaces: string[]
onAdvance: (msg: ViewMessage) => void
onError: (message: string) => void
viewId?: string
@ -35,38 +35,38 @@ const ACCEPT =
".txt,.md,.pdf,.doc,.docx,.csv,.png,.jpg,.jpeg,.gif,.webp,.mp3,.wav,.m4a,.mp4,.webm"
export function Upload({
activeTag,
writableTags,
activeNamespace,
writableNamespaces,
onAdvance,
onError,
viewId,
}: Props) {
const { callTool, handoffToModel } = useApp()
const [file, setFile] = useState<File | null>(null)
const [selectedTag, setSelectedTag] = useState<string | null>(
activeTag ?? writableTags[0] ?? null,
const [selectedNamespace, setSelectedNamespace] = useState<string | null>(
activeNamespace ?? writableNamespaces[0] ?? null,
)
const [uploading, setUploading] = useState(false)
const options = useMemo(
() =>
writableTags.map((tag) => ({
value: tag,
label: formatTagLabel(tag),
description: tag,
writableNamespaces.map((namespace) => ({
value: namespace,
label: formatNamespaceLabel(namespace),
description: namespace,
})),
[writableTags],
[writableNamespaces],
)
const canUpload = !!file && !!selectedTag && !uploading
const canUpload = !!file && !!selectedNamespace && !uploading
const handleUpload = async () => {
if (!file || !selectedTag) return
if (!file || !selectedNamespace) return
setUploading(true)
try {
const preparation = await callTool(
"prepare-file-upload",
{},
{ namespace: selectedNamespace },
uploadPreparationSchema,
)
if (!preparation.ok || !preparation.data) {
@ -76,7 +76,6 @@ export function Upload({
const formData = new FormData()
formData.append("file", file, file.name)
formData.append("containerTag", selectedTag)
formData.append(
"metadata",
JSON.stringify({ sm_source: "supermemory-mcp" }),
@ -107,16 +106,16 @@ export function Upload({
viewId,
id: uploaded.data.id,
fileName: file.name,
containerTag: selectedTag,
namespace: selectedNamespace,
}
onAdvance(result)
await handoffToModel({
context: `Supermemory widget action completed. "${file.name}" was uploaded to space "${selectedTag}" with document ID "${uploaded.data.id}". It is already uploaded; do not upload it again.`,
message: `I used the Supermemory widget to upload "${file.name}" to space "${selectedTag}" (document ID: ${uploaded.data.id}). The file is already uploaded; do not upload it again.`,
context: `Supermemory widget action completed. "${file.name}" was uploaded to space "${selectedNamespace}" with document ID "${uploaded.data.id}". It is already uploaded; do not upload it again.`,
message: `I used the Supermemory widget to upload "${file.name}" to space "${selectedNamespace}" (document ID: ${uploaded.data.id}). The file is already uploaded; do not upload it again.`,
structuredContent: {
supermemory: {
action: "file-uploaded",
activeSpace: selectedTag,
activeSpace: selectedNamespace,
documentId: uploaded.data.id,
fileName: file.name,
},
@ -167,12 +166,12 @@ export function Upload({
/>
)}
{writableTags.length > 0 ? (
{writableNamespaces.length > 0 ? (
<Field label="Space">
<SpaceSelect
onValueChange={setSelectedTag}
onValueChange={setSelectedNamespace}
options={options}
value={selectedTag}
value={selectedNamespace}
/>
</Field>
) : null}

View file

@ -84,7 +84,7 @@
"posthog-node": "^5.18.0",
"react": "^19.2.4",
"react-dom": "^19.2.4",
"supermemory": "^4.0.0",
"supermemory": "^5.0.0",
"tailwind-merge": "^3.4.0",
"zod": "^4.4.3",
},
@ -4605,7 +4605,7 @@
"supermemory-mcp/@vitejs/plugin-react": ["@vitejs/plugin-react@4.7.0", "", { "dependencies": { "@babel/core": "^7.28.0", "@babel/plugin-transform-react-jsx-self": "^7.27.1", "@babel/plugin-transform-react-jsx-source": "^7.27.1", "@rolldown/pluginutils": "1.0.0-beta.27", "@types/babel__core": "^7.20.5", "react-refresh": "^0.17.0" }, "peerDependencies": { "vite": "^4.2.0 || ^5.0.0 || ^6.0.0 || ^7.0.0" } }, "sha512-gUu9hwfWvvEDBBmgtAowQCojwZmJ5mcLn3aufeCsitijs3+f2NsrPtlAWIR6OPiqljl96GVCUbLe0HyqIpVaoA=="],
"supermemory-mcp/supermemory": ["supermemory@4.25.4", "", { "bin": { "supermemory": "bin/cli" } }, "sha512-97ME3rlmu7OmsXJTb9OgXOD+3VUv4Wej0ZX9xezG+LKkMwrzi4xeeAZaOJFcr0oI/QQjcHG2WOzm+und1e7MFA=="],
"supermemory-mcp/supermemory": ["supermemory@5.0.0", "", { "bin": { "supermemory": "bin/cli.mjs" } }, "sha512-qnnGcJ1UHFt8Df/j8U4c1SooMV2axkg03jhrTIDOPnjma32aeXxaao+Z5Q/U7EyorNN7Vn82PY3Rd6lGInEgAA=="],
"supermemory-mcp/typescript": ["typescript@5.9.3", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw=="],