Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 61 additions & 0 deletions packages/agent-blackboard/src/mcp/client-marker.test.mts
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import { Client } from '@modelcontextprotocol/sdk/client/index.js'
import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js'
import { describe, expect, it } from 'vitest'
import { sendJson, startHttpFixture } from '../__tests__/http-fixture.mjs'
import { useTempDirs, writePersisted } from '../__tests__/temp-worktree.mjs'
import { createMcpServer } from './server.mjs'
import { withClientHarnessMarker } from './session-resolution.mjs'

const tempDir = useTempDirs()
const cwd = '/nonexistent-agent-blackboard-mcp'

describe('withClientHarnessMarker', () => {
it('marks Cursor clients and leaves everything else untouched', () => {
const base = { env: { AGENT_BLACKBOARD_URL: 'u' }, cwd }
expect(withClientHarnessMarker(base, 'cursor-vscode')).toEqual({
env: { AGENT_BLACKBOARD_URL: 'u', CURSOR_AGENT: '1' },
cwd,
})
expect(withClientHarnessMarker(base, 'Cursor')?.env.CURSOR_AGENT).toBe('1')
expect(base.env).toEqual({ AGENT_BLACKBOARD_URL: 'u' })
expect(withClientHarnessMarker(base, 'claude-code')).toBe(base)
expect(withClientHarnessMarker(base, undefined)).toBe(base)
expect(withClientHarnessMarker(undefined, 'cursor-vscode')).toBeUndefined()
const marked = { env: { CURSOR_AGENT: 'yes' }, cwd }
expect(withClientHarnessMarker(marked, 'cursor-vscode')).toBe(marked)
})
})

async function appendWithoutSessionId(clientName: string, root: string): Promise<string[]> {
const urls: string[] = []
const fixture = await startHttpFixture((req, res) => {
urls.push(req.url)
sendJson(res, 201, { sessionId: 's', createdAt: 'now', data: {} })
})
try {
const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair()
const server = createMcpServer({ baseUrl: fixture.baseUrl, token: 't' }, { env: {}, cwd: root })
const client = new Client({ name: clientName, version: '1' })
await Promise.all([server.connect(serverTransport), client.connect(clientTransport)])
const result = await client.callTool({ name: 'entry_append', arguments: { data: {} } })
if (result.isError) urls.push(`error: ${JSON.stringify(result.content)}`)
await client.close()
return urls
} finally {
await fixture.close()
}
}

describe('MCP session resolution for Cursor clients', () => {
it('falls back to the persisted Cursor id only when the client is Cursor', async () => {
const root = await tempDir({ git: true })
await writePersisted(root, 'cursor', 'cursor-persisted\n')

expect(await appendWithoutSessionId('cursor-vscode', root)).toEqual([
'/sessions/cursor-persisted/entries',
])
const other = await appendWithoutSessionId('some-client', root)
expect(other).toHaveLength(1)
expect(other[0]).toMatch(/^error: .*no session id/)
})
})
3 changes: 2 additions & 1 deletion packages/agent-blackboard/src/mcp/server.mts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { dispatchTool } from './dispatch.mjs'
import { ENTRY_TOOLS } from './schemas.mjs'
import type { CallToolResult } from '@modelcontextprotocol/sdk/types.js'
import type { ClientConfig } from '../client/types.mjs'
import { withClientHarnessMarker } from './session-resolution.mjs'
import type { SessionResolutionContext } from './session-resolution.mjs'

const SERVER_INFO = { name: 'agent-blackboard', version: '0.0.0' }
Expand All @@ -29,7 +30,7 @@ export function createMcpServer(
request.params.name,
request.params.arguments ?? {},
config,
resolution,
withClientHarnessMarker(resolution, server.getClientVersion()?.name),
)
return { content: [{ type: 'text', text: JSON.stringify(result) }] }
} catch (err) {
Expand Down
15 changes: 15 additions & 0 deletions packages/agent-blackboard/src/mcp/session-resolution.mts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,21 @@ export interface SessionResolutionContext {
cwd: string
}

/**
* A Cursor-launched MCP server usually gets only the URL and token from `mcp.json`, not
* `CURSOR_AGENT`. When the MCP client identifies itself as Cursor, mark the resolution env as
* Cursor so an omitted `sessionId` can fall back to the persisted Cursor id. Only the marker is
* set, never a runtime hint, so explicit harness env still takes precedence as usual.
*/
export function withClientHarnessMarker(
resolution: SessionResolutionContext | undefined,
clientName: string | undefined,
): SessionResolutionContext | undefined {
if (resolution === undefined || resolution.env.CURSOR_AGENT) return resolution
if (!clientName?.toLowerCase().includes('cursor')) return resolution
return { ...resolution, env: { ...resolution.env, CURSOR_AGENT: '1' } }
}

/**
* An explicit `sessionId` wins and is passed through (the server validates it). When omitted and
* a resolution context is available, the id is resolved from the harness environment or the
Expand Down
49 changes: 49 additions & 0 deletions packages/agent-blackboard/src/session-id/persist-atomic.test.mts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import { lstat, mkdir, readdir, readFile, symlink, writeFile } from 'node:fs/promises'
import { join } from 'node:path'
import { describe, expect, it } from 'vitest'
import { useTempDirs } from '../__tests__/temp-worktree.mjs'
import {
persistRealSessionId,
resolveAndPersistRootCodexSessionId,
sessionPersistPath,
} from './persist.mjs'

const tempDir = useTempDirs()

describe('atomic persisted session id writes', () => {
it('writes with owner-only permissions and leaves no temp files behind', async () => {
const root = await tempDir({ git: true })
persistRealSessionId(root, 'cursor', 'cursor-one')
persistRealSessionId(root, 'cursor', 'cursor-two')
const path = sessionPersistPath(root, 'cursor')
expect(await readFile(path, 'utf8')).toBe('cursor-two\n')
expect((await lstat(path)).mode & 0o777).toBe(0o600)
expect(await readdir(join(root, '.local'))).toEqual(['cursor-session-id'])
})

it('replaces a symlink at the target instead of writing through it', async () => {
const root = await tempDir({ git: true })
const outside = join(await tempDir(), 'victim')
await writeFile(outside, 'untouched\n', 'utf8')
await mkdir(join(root, '.local'), { recursive: true })
const path = sessionPersistPath(root, 'codex')
await symlink(outside, path)

resolveAndPersistRootCodexSessionId({ root, payloadId: 'codex-real' })

expect(await readFile(outside, 'utf8')).toBe('untouched\n')
expect((await lstat(path)).isSymbolicLink()).toBe(false)
expect(await readFile(path, 'utf8')).toBe('codex-real\n')
})

it('removes the temp file when the rename fails', async () => {
const root = await tempDir({ git: true })
const path = sessionPersistPath(root, 'codex')
await mkdir(join(path, 'occupied'), { recursive: true })

expect(() => resolveAndPersistRootCodexSessionId({ root, payloadId: 'codex-real' })).toThrow(
'failed to persist root Codex session id',
)
expect(await readdir(join(root, '.local'))).toEqual(['codex-session-id'])
})
})
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ vi.mock('node:fs', async (importOriginal) => {
...actual,
mkdirSync: vi.fn(),
writeFileSync: vi.fn(),
renameSync: vi.fn(),
readFileSync: vi.fn(() => 'someone-else\n'),
}
})
Expand Down
16 changes: 14 additions & 2 deletions packages/agent-blackboard/src/session-id/persist.mts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { randomUUID } from 'node:crypto'
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs'
import { dirname, join, resolve } from 'node:path'
import { isValidSessionId, sanitizeSessionId } from './valid-id.mjs'

Expand Down Expand Up @@ -54,10 +54,22 @@ export function readPersistedSessionId(
}
}

/**
* Writes to a unique temp file beside the target and renames it into place, so a concurrent reader
* sees either the old or the new id, never a truncated file. `rename` replaces a symlink at the
* target instead of following it, and the `wx` flag refuses to follow one at the temp path.
*/
function writePersistFile(root: string, harness: PersistedHarness, sessionId: string): void {
const path = sessionPersistPath(root, harness)
mkdirSync(dirname(path), { recursive: true })
writeFileSync(path, `${sessionId}\n`, { encoding: 'utf8' })
const temp = `${path}.${process.pid}.${randomUUID()}.tmp`
try {
writeFileSync(temp, `${sessionId}\n`, { encoding: 'utf8', flag: 'wx', mode: 0o600 })
renameSync(temp, path)
} catch (err) {
rmSync(temp, { force: true })
throw err
}
}

function tryWritePersistFile(root: string, harness: PersistedHarness, sessionId: string): void {
Expand Down
Loading