@cslug/ai 0.4.1 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +5 -2
- package/docs/README.md +182 -3
- package/docs/api.md +44 -0
- package/migrations/00000000_000500_cslug_ai.sql +48 -0
- package/package.json +24 -5
- package/src/agent.ts +168 -0
- package/src/ai-eval-command.ts +100 -0
- package/src/ai-provider.ts +187 -0
- package/src/ai-stream.ts +31 -0
- package/src/ai.ts +329 -0
- package/src/budget.ts +103 -0
- package/src/conversation-store.ts +79 -0
- package/src/conversations.ts +251 -0
- package/src/drivers.ts +249 -0
- package/src/embedders.ts +133 -0
- package/src/fake.ts +165 -0
- package/src/index.ts +88 -4
- package/src/mcp-client.ts +154 -0
- package/src/mcp.ts +75 -0
- package/src/model.ts +111 -0
- package/src/search-tools.ts +163 -0
- package/src/sse.ts +35 -0
package/src/embedders.ts
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
import { CslugError } from '@cslug/core'
|
|
2
|
+
import type { Budget } from './budget'
|
|
3
|
+
import { postJson } from './model'
|
|
4
|
+
|
|
5
|
+
/** `config/ai.ts` → `embeddings`: the model `@cslug/search` embeds documents and queries with. */
|
|
6
|
+
export type EmbeddingsConfig =
|
|
7
|
+
| {
|
|
8
|
+
driver: 'openai-compatible'
|
|
9
|
+
/** The API root (`https://api.openai.com/v1`, `http://localhost:11434/v1` for Ollama). */
|
|
10
|
+
baseUrl: string
|
|
11
|
+
apiKey?: string
|
|
12
|
+
model: string
|
|
13
|
+
/** Shorter vectors, for models that support it. */
|
|
14
|
+
dimensions?: number
|
|
15
|
+
}
|
|
16
|
+
| {
|
|
17
|
+
driver: 'voyage'
|
|
18
|
+
/** Default: `VOYAGE_API_KEY`. */
|
|
19
|
+
apiKey?: string
|
|
20
|
+
/** `voyage-3.5`, `voyage-3.5-lite`, `voyage-multilingual-2`… */
|
|
21
|
+
model: string
|
|
22
|
+
dimensions?: number
|
|
23
|
+
baseUrl?: string
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
type Json = Record<string, unknown>
|
|
27
|
+
|
|
28
|
+
/** What `@cslug/search`'s `Embedder` asks for (structural: this package does not import search). */
|
|
29
|
+
export interface TextEmbedder {
|
|
30
|
+
readonly model: string
|
|
31
|
+
embed(texts: string[], purpose: 'document' | 'query'): Promise<number[][]>
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** The vectors of a `/embeddings` response, in input order. */
|
|
35
|
+
function vectorsOf(json: Json, count: number): number[][] {
|
|
36
|
+
const data = ((json.data ?? []) as { embedding: number[]; index: number }[]).slice().sort((a, b) => a.index - b.index)
|
|
37
|
+
if (data.length !== count)
|
|
38
|
+
throw new CslugError('ai.embeddings', `The embeddings API returned ${data.length} vectors for ${count} texts`)
|
|
39
|
+
return data.map((d) => d.embedding)
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** Embeddings over `fetch`, charged to the daily budget (`ai.budget`) as input tokens of `model`. */
|
|
43
|
+
abstract class HttpEmbedder implements TextEmbedder {
|
|
44
|
+
/** Identifies the vectors: the model, and the dimensions when set (`voyage-3.5@512`). */
|
|
45
|
+
abstract readonly model: string
|
|
46
|
+
/** The model's name as priced in the budget (`ai.prices`). */
|
|
47
|
+
protected abstract readonly priced: string
|
|
48
|
+
constructor(protected readonly budget?: () => Budget | undefined) {}
|
|
49
|
+
|
|
50
|
+
protected abstract request(texts: string[], purpose: 'document' | 'query'): [string, Record<string, string>, Json]
|
|
51
|
+
protected abstract tokens(json: Json): number
|
|
52
|
+
|
|
53
|
+
async embed(texts: string[], purpose: 'document' | 'query'): Promise<number[][]> {
|
|
54
|
+
if (!texts.length) return []
|
|
55
|
+
const budget = this.budget?.()
|
|
56
|
+
await budget?.check()
|
|
57
|
+
const json = (await (await postJson(...this.request(texts, purpose))).json()) as Json
|
|
58
|
+
await budget?.charge(this.priced, { inputTokens: this.tokens(json), outputTokens: 0 })
|
|
59
|
+
return vectorsOf(json, texts.length)
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** Any OpenAI-compatible `/embeddings` endpoint (OpenAI, Ollama, vLLM, LM Studio…). */
|
|
64
|
+
export class OpenAiCompatibleEmbedder extends HttpEmbedder {
|
|
65
|
+
readonly model: string
|
|
66
|
+
protected readonly priced: string
|
|
67
|
+
constructor(
|
|
68
|
+
private readonly config: Extract<EmbeddingsConfig, { driver: 'openai-compatible' }>,
|
|
69
|
+
budget?: () => Budget | undefined,
|
|
70
|
+
) {
|
|
71
|
+
super(budget)
|
|
72
|
+
this.model = config.dimensions ? `${config.model}@${config.dimensions}` : config.model
|
|
73
|
+
this.priced = config.model
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
protected request(texts: string[]): [string, Record<string, string>, Json] {
|
|
77
|
+
const headers: Record<string, string> = this.config.apiKey ? { authorization: `Bearer ${this.config.apiKey}` } : {}
|
|
78
|
+
return [
|
|
79
|
+
`${this.config.baseUrl.replace(/\/$/, '')}/embeddings`,
|
|
80
|
+
headers,
|
|
81
|
+
{
|
|
82
|
+
model: this.config.model,
|
|
83
|
+
input: texts,
|
|
84
|
+
...(this.config.dimensions ? { dimensions: this.config.dimensions } : {}),
|
|
85
|
+
},
|
|
86
|
+
]
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
protected tokens(json: Json): number {
|
|
90
|
+
const usage = (json.usage ?? {}) as Json
|
|
91
|
+
return Number(usage.prompt_tokens ?? usage.total_tokens ?? 0)
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** Voyage AI embeddings (the provider Anthropic recommends): queries and documents are embedded differently. */
|
|
96
|
+
export class VoyageEmbedder extends HttpEmbedder {
|
|
97
|
+
readonly model: string
|
|
98
|
+
protected readonly priced: string
|
|
99
|
+
constructor(
|
|
100
|
+
private readonly config: Extract<EmbeddingsConfig, { driver: 'voyage' }>,
|
|
101
|
+
budget?: () => Budget | undefined,
|
|
102
|
+
) {
|
|
103
|
+
super(budget)
|
|
104
|
+
this.model = config.dimensions ? `${config.model}@${config.dimensions}` : config.model
|
|
105
|
+
this.priced = config.model
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
protected request(texts: string[], purpose: 'document' | 'query'): [string, Record<string, string>, Json] {
|
|
109
|
+
const key = this.config.apiKey ?? process.env.VOYAGE_API_KEY
|
|
110
|
+
if (!key) throw new CslugError('ai.no_key', 'Set VOYAGE_API_KEY (or embeddings.apiKey in config/ai.ts)')
|
|
111
|
+
return [
|
|
112
|
+
`${(this.config.baseUrl ?? 'https://api.voyageai.com/v1').replace(/\/$/, '')}/embeddings`,
|
|
113
|
+
{ authorization: `Bearer ${key}` },
|
|
114
|
+
{
|
|
115
|
+
model: this.config.model,
|
|
116
|
+
input: texts,
|
|
117
|
+
input_type: purpose,
|
|
118
|
+
...(this.config.dimensions ? { output_dimension: this.config.dimensions } : {}),
|
|
119
|
+
},
|
|
120
|
+
]
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
protected tokens(json: Json): number {
|
|
124
|
+
return Number(((json.usage ?? {}) as Json).total_tokens ?? 0)
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/** The embedder for `config/ai.ts` → `embeddings`. */
|
|
129
|
+
export function embedderFor(config: EmbeddingsConfig, budget?: () => Budget | undefined): TextEmbedder {
|
|
130
|
+
if (config.driver === 'voyage') return new VoyageEmbedder(config, budget)
|
|
131
|
+
if (config.driver === 'openai-compatible') return new OpenAiCompatibleEmbedder(config, budget)
|
|
132
|
+
throw new CslugError('ai.unknown_driver', `Unknown embeddings driver "${(config as { driver: string }).driver}"`)
|
|
133
|
+
}
|
package/src/fake.ts
ADDED
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
|
|
2
|
+
import { dirname, join } from 'node:path'
|
|
3
|
+
import { type Application, CslugError, Logger } from '@cslug/core'
|
|
4
|
+
import type { Agent, AgentSettings, RunOptions } from './agent'
|
|
5
|
+
import { Ai, type AiConfig, type AiResult, type RunMeta } from './ai'
|
|
6
|
+
import { AiStream } from './ai-stream'
|
|
7
|
+
import type { Message } from './model'
|
|
8
|
+
|
|
9
|
+
type AgentClass<A extends Agent = Agent> = abstract new (...args: never[]) => A
|
|
10
|
+
/** A recorded run: the agent, its input and context. */
|
|
11
|
+
export type AiRun = { agent: AgentSettings } & Required<RunOptions>
|
|
12
|
+
|
|
13
|
+
/** `tests/fixtures/ai/<name>.json`: a real run, written by `cslug ai:record`, replayed by `t.ai.fixture()`. */
|
|
14
|
+
export type AiFixture = {
|
|
15
|
+
agent: string
|
|
16
|
+
input: string
|
|
17
|
+
context: Record<string, unknown>
|
|
18
|
+
/** The conversation before this run, when it continued one. */
|
|
19
|
+
history?: Message[]
|
|
20
|
+
/** The model's answer before validation (parsed JSON, or the text). */
|
|
21
|
+
output: unknown
|
|
22
|
+
model: string
|
|
23
|
+
recordedAt: string
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** The folder fixtures live in, under the app root. */
|
|
27
|
+
export const FIXTURES_DIR = 'tests/fixtures/ai'
|
|
28
|
+
|
|
29
|
+
const textOf = (raw: unknown) => (typeof raw === 'string' ? raw : JSON.stringify(raw))
|
|
30
|
+
|
|
31
|
+
export const readFixture = (path: string): AiFixture => JSON.parse(readFileSync(path, 'utf8')) as AiFixture
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* AI in tests (`testApp({ fakes: ['ai'] })` → `t.ai`): no provider is called. `respond(Agent, output)` gives an agent
|
|
35
|
+
* its answer (checked against its `output` schema, so fixtures stay valid); every run is recorded.
|
|
36
|
+
*/
|
|
37
|
+
export class AiFake extends Ai {
|
|
38
|
+
readonly runs: AiRun[] = []
|
|
39
|
+
private readonly answers = new Map<AgentClass, (run: AiRun) => unknown>()
|
|
40
|
+
private real?: Ai
|
|
41
|
+
|
|
42
|
+
constructor(app: Application) {
|
|
43
|
+
super(app, {}, Logger.null())
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** An agent's answer: a value, or a function of the run (its input, context, history). */
|
|
47
|
+
respond<A extends Agent>(agent: AgentClass<A>, answer: (run: AiRun) => unknown): this
|
|
48
|
+
respond<A extends Agent>(agent: AgentClass<A>, output: unknown): this
|
|
49
|
+
respond<A extends Agent>(agent: AgentClass<A>, output: unknown): this {
|
|
50
|
+
this.answers.set(agent, typeof output === 'function' ? (output as (run: AiRun) => unknown) : () => output)
|
|
51
|
+
return this
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Answer an agent with a recorded fixture, `tests/fixtures/ai/<name>.json`. `cslug ai:record` runs the test against
|
|
56
|
+
* the real provider and writes the fixtures that are missing (`--all`: every one).
|
|
57
|
+
*/
|
|
58
|
+
fixture<A extends Agent>(agent: AgentClass<A>, name: string): this {
|
|
59
|
+
const path = join(this.app.rootDir, FIXTURES_DIR, `${name}.json`)
|
|
60
|
+
return this.respond(agent, async (run: AiRun) => {
|
|
61
|
+
const mode = process.env.CSLUG_AI_RECORD
|
|
62
|
+
if (mode === 'all' || (mode && !existsSync(path))) return this.record(run, path)
|
|
63
|
+
if (!existsSync(path))
|
|
64
|
+
throw new CslugError(
|
|
65
|
+
'ai.no_fixture',
|
|
66
|
+
`No AI fixture ${FIXTURES_DIR}/${name}.json: record it with \`cslug ai:record <this test file>\``,
|
|
67
|
+
)
|
|
68
|
+
return readFixture(path).output
|
|
69
|
+
})
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** Run against the real provider (config `ai`) and write the fixture. */
|
|
73
|
+
private async record(run: AiRun, path: string): Promise<unknown> {
|
|
74
|
+
this.real ??= new Ai(this.app, this.app.config<AiConfig | undefined>('ai') ?? {}, Logger.null())
|
|
75
|
+
const result = await this.real.result(run.agent, run)
|
|
76
|
+
const fixture: AiFixture = {
|
|
77
|
+
agent: run.agent.constructor.name,
|
|
78
|
+
input: run.input,
|
|
79
|
+
context: run.context,
|
|
80
|
+
...(run.history.length ? { history: run.history } : {}),
|
|
81
|
+
output: result.raw,
|
|
82
|
+
model: result.model,
|
|
83
|
+
recordedAt: new Date().toISOString(),
|
|
84
|
+
}
|
|
85
|
+
mkdirSync(dirname(path), { recursive: true })
|
|
86
|
+
writeFileSync(path, `${JSON.stringify(fixture, null, 2)}\n`)
|
|
87
|
+
process.stderr.write(`recorded ${path} (${result.model}, $${(result.costUsd ?? 0).toFixed(4)})\n`)
|
|
88
|
+
return result.raw
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** The fake's answer as a run result: no provider call, no cost; `messages` continue the `history`. */
|
|
92
|
+
override async result(
|
|
93
|
+
agent: AgentSettings,
|
|
94
|
+
{ input, context = {}, history = [] }: RunOptions,
|
|
95
|
+
_meta?: RunMeta,
|
|
96
|
+
): Promise<AiResult> {
|
|
97
|
+
const run: AiRun = { agent, input, context, history }
|
|
98
|
+
this.runs.push(run)
|
|
99
|
+
const answer = [...this.answers].find(([cls]) => agent instanceof cls)?.[1]
|
|
100
|
+
if (!answer)
|
|
101
|
+
throw new Error(`No fake answer for ${agent.constructor.name}: t.ai.respond(${agent.constructor.name}, …)`)
|
|
102
|
+
const raw = await answer(run)
|
|
103
|
+
const value = agent.output ? this.validate(agent, raw) : String(raw)
|
|
104
|
+
return {
|
|
105
|
+
runId: Bun.randomUUIDv7(),
|
|
106
|
+
value,
|
|
107
|
+
raw,
|
|
108
|
+
model: 'fake',
|
|
109
|
+
steps: 1,
|
|
110
|
+
usage: { inputTokens: 0, outputTokens: 0 },
|
|
111
|
+
costUsd: 0,
|
|
112
|
+
messages: [
|
|
113
|
+
...history,
|
|
114
|
+
{ role: 'user', content: [{ type: 'text', text: input }] },
|
|
115
|
+
{ role: 'assistant', content: [{ type: 'text', text: textOf(raw) }] },
|
|
116
|
+
],
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** The whole answer as one piece of text, then the result. */
|
|
121
|
+
override stream(agent: AgentSettings, options: RunOptions, _meta?: RunMeta): AiStream {
|
|
122
|
+
const result = this.result(agent, options)
|
|
123
|
+
return new AiStream(
|
|
124
|
+
(async function* () {
|
|
125
|
+
const done = await result
|
|
126
|
+
yield { type: 'text' as const, text: textOf(done.raw) }
|
|
127
|
+
yield { type: 'result' as const, result: done }
|
|
128
|
+
})(),
|
|
129
|
+
)
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
override async close(): Promise<void> {
|
|
133
|
+
await this.real?.close()
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
ran<A extends Agent>(agent: AgentClass<A>): AiRun[] {
|
|
137
|
+
return this.runs.filter((r) => r.agent instanceof agent)
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
assertRan<A extends Agent>(agent: AgentClass<A>, where?: (run: AiRun) => boolean): void {
|
|
141
|
+
if (!this.ran(agent).some((r) => !where || where(r)))
|
|
142
|
+
throw new Error(
|
|
143
|
+
`Expected ${agent.name} to run${where ? ' (matching)' : ''}; ran: ${this.runs.map((r) => r.agent.constructor.name).join(', ') || 'none'}`,
|
|
144
|
+
)
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
assertNotRan<A extends Agent>(agent: AgentClass<A>): void {
|
|
148
|
+
if (this.ran(agent).length) throw new Error(`Expected ${agent.name} not to run`)
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
let embedderFake: { token: unknown; create: () => unknown } | undefined
|
|
153
|
+
|
|
154
|
+
/** Set by `AiProvider` when it binds @cslug/search's `Embedder`: what the AI fake swaps it for. */
|
|
155
|
+
export function setFakeEmbedder(token: unknown, create: () => unknown): void {
|
|
156
|
+
embedderFake = { token, create }
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/** `fakes: ['ai']`: `Ai` is an `AiFake`, and a configured `Embedder` a `FakeEmbedder` (no provider is called). */
|
|
160
|
+
export function installAiFake(app: Application): AiFake {
|
|
161
|
+
const fake = new AiFake(app)
|
|
162
|
+
app.swap(Ai, fake)
|
|
163
|
+
if (embedderFake && app.has(embedderFake.token as never)) app.swap(embedderFake.token as never, embedderFake.create())
|
|
164
|
+
return fake
|
|
165
|
+
}
|
package/src/index.ts
CHANGED
|
@@ -1,6 +1,90 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @cslug/ai:
|
|
3
|
-
*
|
|
4
|
-
* Not implemented yet. See docs/packages.md and docs/implementation-plan.md.
|
|
2
|
+
* @cslug/ai: agents and tools as `@inject()` classes, structured output validated by `v` schemas, prompts as
|
|
3
|
+
* Markdown files, streaming to the browser, Anthropic and OpenAI-compatible providers over `fetch`, a test fake.
|
|
5
4
|
*/
|
|
6
|
-
export {
|
|
5
|
+
export {
|
|
6
|
+
Agent,
|
|
7
|
+
type AgentOutput,
|
|
8
|
+
type AgentSettings,
|
|
9
|
+
fillPrompt,
|
|
10
|
+
type Instructions,
|
|
11
|
+
PROMPT_VARIABLE,
|
|
12
|
+
Prompt,
|
|
13
|
+
prompt,
|
|
14
|
+
type RunnableTool,
|
|
15
|
+
type RunOptions,
|
|
16
|
+
renderInstructions,
|
|
17
|
+
Tool,
|
|
18
|
+
type ToolClass,
|
|
19
|
+
} from './agent'
|
|
20
|
+
export { Ai, type AiConfig, AiOutputError, type AiResult, type RunMeta, type RunRecord } from './ai'
|
|
21
|
+
export { AiEvalCommand, jsonDiff } from './ai-eval-command'
|
|
22
|
+
export { AiPromptsCommand, AiProvider, AiRecordCommand, McpServeCommand } from './ai-provider'
|
|
23
|
+
export { AiStream } from './ai-stream'
|
|
24
|
+
export {
|
|
25
|
+
AiBudgetAlert,
|
|
26
|
+
AiBudgetError,
|
|
27
|
+
Budget,
|
|
28
|
+
type BudgetConfig,
|
|
29
|
+
costOf,
|
|
30
|
+
MODEL_PRICES,
|
|
31
|
+
type ModelPrice,
|
|
32
|
+
} from './budget'
|
|
33
|
+
export { AI_MIGRATIONS } from './conversation-store'
|
|
34
|
+
export {
|
|
35
|
+
Conversation,
|
|
36
|
+
type ConversationRow,
|
|
37
|
+
type ConversationStore,
|
|
38
|
+
Conversations,
|
|
39
|
+
type FindOptions,
|
|
40
|
+
type OwnerRef,
|
|
41
|
+
type StartOptions,
|
|
42
|
+
} from './conversations'
|
|
43
|
+
export {
|
|
44
|
+
type AnthropicConfig,
|
|
45
|
+
AnthropicProvider,
|
|
46
|
+
type OpenAiCompatibleConfig,
|
|
47
|
+
OpenAiCompatibleProvider,
|
|
48
|
+
} from './drivers'
|
|
49
|
+
export {
|
|
50
|
+
type EmbeddingsConfig,
|
|
51
|
+
embedderFor,
|
|
52
|
+
OpenAiCompatibleEmbedder,
|
|
53
|
+
type TextEmbedder,
|
|
54
|
+
VoyageEmbedder,
|
|
55
|
+
} from './embedders'
|
|
56
|
+
export { AiFake, type AiFixture, type AiRun, FIXTURES_DIR, installAiFake, setFakeEmbedder } from './fake'
|
|
57
|
+
export {
|
|
58
|
+
asMcpTools,
|
|
59
|
+
discoverTools,
|
|
60
|
+
handleMcp,
|
|
61
|
+
MCP_VERSIONS,
|
|
62
|
+
type McpCaller,
|
|
63
|
+
type McpOptions,
|
|
64
|
+
type McpReply,
|
|
65
|
+
mcpTools,
|
|
66
|
+
} from './mcp'
|
|
67
|
+
export { McpConnection, type McpServerConfig, McpTools, mcp } from './mcp-client'
|
|
68
|
+
export {
|
|
69
|
+
AiRefusalError,
|
|
70
|
+
type Block,
|
|
71
|
+
type Effort,
|
|
72
|
+
type Message,
|
|
73
|
+
type ModelRequest,
|
|
74
|
+
type ModelResponse,
|
|
75
|
+
modelSchema,
|
|
76
|
+
type Provider,
|
|
77
|
+
type StreamEvent,
|
|
78
|
+
type ToolSpec,
|
|
79
|
+
type Usage,
|
|
80
|
+
} from './model'
|
|
81
|
+
export {
|
|
82
|
+
CONVERSATION_KEY,
|
|
83
|
+
type ConversationScope,
|
|
84
|
+
currentConversation,
|
|
85
|
+
recallTool,
|
|
86
|
+
type SearchableIndex,
|
|
87
|
+
type SearchToolOptions,
|
|
88
|
+
searchTool,
|
|
89
|
+
} from './search-tools'
|
|
90
|
+
export { sse } from './sse'
|
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
import { CslugError } from '@cslug/core'
|
|
2
|
+
import { exposeMcp, type McpOptions } from './mcp'
|
|
3
|
+
import { sseEvents } from './model'
|
|
4
|
+
|
|
5
|
+
/** `config/ai.ts` → `mcp.<name>`: a streamable HTTP endpoint, or a command speaking MCP on stdio. */
|
|
6
|
+
export type McpServerConfig =
|
|
7
|
+
| { url: string; headers?: Record<string, string> }
|
|
8
|
+
| { command: string[]; env?: Record<string, string> }
|
|
9
|
+
|
|
10
|
+
const MODERN = '2026-07-28'
|
|
11
|
+
const LEGACY = '2025-11-25'
|
|
12
|
+
const CLIENT = { name: 'cslug', version: '0' }
|
|
13
|
+
type Reply = { id?: unknown; result?: Record<string, unknown>; error?: { code: number; message: string } }
|
|
14
|
+
|
|
15
|
+
/** One connection to an MCP server: the version is probed (`server/discover`, else `initialize`) on first use. */
|
|
16
|
+
export class McpConnection {
|
|
17
|
+
private version?: string
|
|
18
|
+
private session?: string
|
|
19
|
+
private nextId = 1
|
|
20
|
+
private proc?: Bun.Subprocess<'pipe', 'pipe', 'inherit'>
|
|
21
|
+
private readonly waiting = new Map<number, (reply: Reply) => void>()
|
|
22
|
+
|
|
23
|
+
constructor(
|
|
24
|
+
readonly name: string,
|
|
25
|
+
private readonly config: McpServerConfig,
|
|
26
|
+
) {}
|
|
27
|
+
|
|
28
|
+
/** A request; a JSON-RPC error is an `ai.mcp` error. */
|
|
29
|
+
async request(method: string, params: Record<string, unknown> = {}): Promise<Record<string, unknown>> {
|
|
30
|
+
if (!this.version) await this.connect()
|
|
31
|
+
const reply = await this.send(method, params)
|
|
32
|
+
if (reply?.error) throw new CslugError('ai.mcp', `${this.name}: ${reply.error.message} (${reply.error.code})`)
|
|
33
|
+
return reply?.result ?? {}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
private async connect() {
|
|
37
|
+
this.version = MODERN
|
|
38
|
+
const discovered = await this.send('server/discover', {}).catch(() => undefined)
|
|
39
|
+
if ((discovered?.result?.supportedVersions as string[] | undefined)?.includes(MODERN)) return
|
|
40
|
+
this.version = undefined // an older server: the initialize handshake
|
|
41
|
+
const init = await this.send('initialize', { protocolVersion: LEGACY, capabilities: {}, clientInfo: CLIENT })
|
|
42
|
+
if (!init?.result) throw new CslugError('ai.mcp', `${this.name}: initialize failed (${init?.error?.message})`)
|
|
43
|
+
this.version = String(init.result.protocolVersion)
|
|
44
|
+
await this.send('notifications/initialized', undefined)
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
private async send(method: string, params: Record<string, unknown> | undefined): Promise<Reply | undefined> {
|
|
48
|
+
const notification = method.startsWith('notifications/')
|
|
49
|
+
const id = notification ? undefined : this.nextId++
|
|
50
|
+
const modern = this.version === MODERN
|
|
51
|
+
const meta = modern
|
|
52
|
+
? {
|
|
53
|
+
_meta: {
|
|
54
|
+
'io.modelcontextprotocol/protocolVersion': MODERN,
|
|
55
|
+
'io.modelcontextprotocol/clientCapabilities': {},
|
|
56
|
+
'io.modelcontextprotocol/clientInfo': CLIENT,
|
|
57
|
+
},
|
|
58
|
+
}
|
|
59
|
+
: {}
|
|
60
|
+
const message = {
|
|
61
|
+
jsonrpc: '2.0',
|
|
62
|
+
...(id ? { id } : {}),
|
|
63
|
+
method,
|
|
64
|
+
...(params || modern ? { params: { ...params, ...meta } } : {}),
|
|
65
|
+
}
|
|
66
|
+
return 'url' in this.config ? this.http(message, id) : this.stdio(message, id)
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
private async http(message: { method: string; params?: Record<string, unknown> }, id?: number) {
|
|
70
|
+
const config = this.config as { url: string; headers?: Record<string, string> }
|
|
71
|
+
const res = await fetch(config.url, {
|
|
72
|
+
method: 'POST',
|
|
73
|
+
headers: {
|
|
74
|
+
'content-type': 'application/json',
|
|
75
|
+
accept: 'application/json, text/event-stream',
|
|
76
|
+
'mcp-method': message.method,
|
|
77
|
+
...(this.version ? { 'mcp-protocol-version': this.version } : {}),
|
|
78
|
+
...(message.method === 'tools/call' ? { 'mcp-name': String(message.params?.name) } : {}),
|
|
79
|
+
...(this.session ? { 'mcp-session-id': this.session } : {}),
|
|
80
|
+
...config.headers,
|
|
81
|
+
},
|
|
82
|
+
body: JSON.stringify(message),
|
|
83
|
+
})
|
|
84
|
+
this.session = res.headers.get('mcp-session-id') ?? this.session
|
|
85
|
+
if (id === undefined || res.status === 202) return undefined
|
|
86
|
+
if (!res.ok && !res.headers.get('content-type')?.includes('json'))
|
|
87
|
+
throw new CslugError('ai.mcp', `${this.name} answered ${res.status}`)
|
|
88
|
+
if (!res.headers.get('content-type')?.includes('event-stream')) return (await res.json()) as Reply
|
|
89
|
+
for await (const { data } of sseEvents(res.body as ReadableStream<Uint8Array>)) {
|
|
90
|
+
const reply = JSON.parse(data) as Reply
|
|
91
|
+
if (reply.id === id) return reply
|
|
92
|
+
}
|
|
93
|
+
throw new CslugError('ai.mcp', `${this.name}: the stream ended without a response`)
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
private async stdio(message: object, id?: number) {
|
|
97
|
+
const proc = this.proc ?? this.spawn()
|
|
98
|
+
const reply = id === undefined ? undefined : new Promise<Reply>((done) => this.waiting.set(id, done))
|
|
99
|
+
proc.stdin.write(`${JSON.stringify(message)}\n`)
|
|
100
|
+
await proc.stdin.flush()
|
|
101
|
+
return reply
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
private spawn() {
|
|
105
|
+
const { command, env } = this.config as { command: string[]; env?: Record<string, string> }
|
|
106
|
+
const proc = Bun.spawn(command, {
|
|
107
|
+
stdin: 'pipe',
|
|
108
|
+
stdout: 'pipe',
|
|
109
|
+
stderr: 'inherit',
|
|
110
|
+
env: { ...process.env, ...env },
|
|
111
|
+
})
|
|
112
|
+
this.proc = proc
|
|
113
|
+
void (async () => {
|
|
114
|
+
const reader = proc.stdout.getReader()
|
|
115
|
+
const decoder = new TextDecoder()
|
|
116
|
+
let buffer = ''
|
|
117
|
+
for (let read = await reader.read(); !read.done; read = await reader.read()) {
|
|
118
|
+
buffer += decoder.decode(read.value, { stream: true })
|
|
119
|
+
for (let end = buffer.indexOf('\n'); end >= 0; end = buffer.indexOf('\n')) {
|
|
120
|
+
const line = buffer.slice(0, end).trim()
|
|
121
|
+
buffer = buffer.slice(end + 1)
|
|
122
|
+
const reply = line ? (JSON.parse(line) as Reply) : undefined
|
|
123
|
+
if (typeof reply?.id === 'number') this.waiting.get(reply.id)?.(reply)
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
})()
|
|
127
|
+
return proc
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
async close(): Promise<void> {
|
|
131
|
+
this.proc?.stdin.end()
|
|
132
|
+
this.proc?.kill()
|
|
133
|
+
await this.proc?.exited
|
|
134
|
+
this.proc = undefined
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/** The tools of an MCP server (all, or the `only` names), for an agent's `tools`. */
|
|
139
|
+
export class McpTools {
|
|
140
|
+
constructor(
|
|
141
|
+
readonly server: string,
|
|
142
|
+
readonly only?: readonly string[],
|
|
143
|
+
) {}
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* `mcp('maps').tools(['route_duration'])`: an MCP server's tools for an agent (spread into `tools`).
|
|
148
|
+
* `@mcp({ ability })`: expose a `Tool` class over MCP.
|
|
149
|
+
*/
|
|
150
|
+
export function mcp(server: string): { tools(only?: readonly string[]): McpTools[] }
|
|
151
|
+
export function mcp(options?: McpOptions): ReturnType<typeof exposeMcp>
|
|
152
|
+
export function mcp(arg?: string | McpOptions) {
|
|
153
|
+
return typeof arg === 'string' ? { tools: (only?: readonly string[]) => [new McpTools(arg, only)] } : exposeMcp(arg)
|
|
154
|
+
}
|
package/src/mcp.ts
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import { existsSync, readdirSync } from 'node:fs'
|
|
2
|
+
import { join } from 'node:path'
|
|
3
|
+
import { type Application, handleMcpMessage, type McpMessage, type McpReply, type McpTool } from '@cslug/core'
|
|
4
|
+
import type { Tool, ToolClass } from './agent'
|
|
5
|
+
|
|
6
|
+
export { MCP_VERSIONS, type McpReply } from '@cslug/core'
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Who may call an exposed tool over HTTP. Default: an authenticated caller (any guard); `public: true` exposes it
|
|
10
|
+
* to anyone; `guard` requires one guard; `ability` an API-token ability (session users pass, as with `ability()`).
|
|
11
|
+
*/
|
|
12
|
+
export type McpOptions = { public?: boolean; guard?: string; ability?: string }
|
|
13
|
+
|
|
14
|
+
const exposed = new Map<ToolClass, McpOptions>()
|
|
15
|
+
|
|
16
|
+
/** `@mcp({ ability: 'mcp:bookings' })` on a `Tool` class: served by `/mcp` and `cslug mcp:serve`. */
|
|
17
|
+
export const exposeMcp =
|
|
18
|
+
(options: McpOptions = {}) =>
|
|
19
|
+
<C extends ToolClass>(cls: C, _context?: ClassDecoratorContext): C => {
|
|
20
|
+
exposed.set(cls, options)
|
|
21
|
+
return cls
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** The tools marked with `@mcp()` (after `discoverTools` imported `app/tools/`). */
|
|
25
|
+
export const mcpTools = (): [ToolClass, McpOptions][] => [...exposed]
|
|
26
|
+
|
|
27
|
+
/** Import every module under `app/tools/`, so their `@mcp()` decorators run. */
|
|
28
|
+
export async function discoverTools(app: Application): Promise<void> {
|
|
29
|
+
const dir = join(app.rootDir, 'app/tools')
|
|
30
|
+
if (!existsSync(dir)) return
|
|
31
|
+
for (const file of (readdirSync(dir, { recursive: true }) as string[]).filter((f) => /(?<!\.test)\.ts$/.test(f)))
|
|
32
|
+
await import(join(dir, file))
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** The caller as the HTTP route sees it: `ctx.auth` when @cslug/auth is installed. */
|
|
36
|
+
export type McpCaller = { check(): boolean; guard?: string; tokenCan(ability: string): boolean } | undefined
|
|
37
|
+
|
|
38
|
+
const allowed = (options: McpOptions, caller: McpCaller | 'local') =>
|
|
39
|
+
caller === 'local' ||
|
|
40
|
+
options.public === true ||
|
|
41
|
+
(!!caller?.check() &&
|
|
42
|
+
(!options.guard || caller.guard === options.guard) &&
|
|
43
|
+
(!options.ability || caller.tokenCan(options.ability)))
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* One MCP message → its response (undefined for a notification). `tools` builds the exposed tools; `caller` is who
|
|
47
|
+
* is asking (`'local'` for stdio: every exposed tool).
|
|
48
|
+
*/
|
|
49
|
+
export async function handleMcp(
|
|
50
|
+
message: McpMessage,
|
|
51
|
+
tools: (cls: ToolClass) => Tool,
|
|
52
|
+
caller: McpCaller | 'local',
|
|
53
|
+
serverInfo = { name: 'cslug', version: '0' },
|
|
54
|
+
): Promise<McpReply | undefined> {
|
|
55
|
+
return handleMcpMessage(message, asMcpTools(tools, caller), serverInfo)
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** The `@mcp()` tools `caller` may use, as MCP tools (arguments validated with the tool's schema). */
|
|
59
|
+
export function asMcpTools(tools: (cls: ToolClass) => Tool, caller: McpCaller | 'local'): McpTool[] {
|
|
60
|
+
return mcpTools()
|
|
61
|
+
.filter(([, options]) => allowed(options, caller))
|
|
62
|
+
.map(([cls]) => {
|
|
63
|
+
const tool = tools(cls)
|
|
64
|
+
return {
|
|
65
|
+
name: tool.name,
|
|
66
|
+
description: tool.description,
|
|
67
|
+
inputSchema: tool.input.toJSONSchema() as Record<string, unknown>,
|
|
68
|
+
call: (args) => {
|
|
69
|
+
const input = tool.input.safeParse(args)
|
|
70
|
+
if (!input.success) throw new Error(`Invalid arguments: ${JSON.stringify(input.error.issues)}`)
|
|
71
|
+
return tool.handle(input.data as never)
|
|
72
|
+
},
|
|
73
|
+
}
|
|
74
|
+
})
|
|
75
|
+
}
|