@onlyne/mcp-core 0.0.0-stage → 3.0.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.
Files changed (4) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +35 -2
  3. package/package.json +33 -4
  4. package/src/index.ts +198 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 dbydd
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,36 @@
1
- # Temporary Holding Version
1
+ # @onlyne/mcp-core
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ An MCP client session and the `ResourceDriver` that maps MCP onto Onlyne resource operations.
4
+
5
+ One MCP server is one Onlyne resource. Its `tools/list` names become the resource's `operations`,
6
+ and `tools/call` becomes the operation call. The official MCP SDK owns the session id, the
7
+ handshake, SSE parsing, and reconnect semantics.
8
+
9
+ ## Operation outcomes
10
+
11
+ | MCP result | Onlyne outcome |
12
+ |---|---|
13
+ | Normal result | `committed`, with `content` and `structuredContent` |
14
+ | `isError: true` | `aborted` for a read-only tool, `unknown` for one with side effects, with the source text in `details` |
15
+ | JSON-RPC protocol error | `invalid_request`; the operation id is never claimed |
16
+ | Transport failure or timeout | `unknown`, with the source text |
17
+
18
+ A tool outside the cached list never leaves the node.
19
+
20
+ ## Example
21
+
22
+ ```ts
23
+ import { McpConnection } from '@onlyne/mcp-core';
24
+
25
+ const connection = new McpConnection({ name: 'hindsight', url: 'http://localhost:8888/mcp/example-bank/' });
26
+ await connection.start();
27
+ const outcome = await connection.call('recall', { query: 'protocol notes' });
28
+ ```
29
+
30
+ ## Runtime
31
+
32
+ The package ships TypeScript source for Bun.
33
+
34
+ ## License
35
+
36
+ MIT.
package/package.json CHANGED
@@ -1,6 +1,35 @@
1
1
  {
2
2
  "name": "@onlyne/mcp-core",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "3.0.0",
4
+ "description": "MCP client session and resource driver that maps tools/list and tools/call onto Onlyne resource operations",
5
+ "type": "module",
6
+ "main": "./src/index.ts",
7
+ "types": "./src/index.ts",
8
+ "license": "MIT",
9
+ "repository": {
10
+ "type": "git",
11
+ "url": "git+https://github.com/dbydd/onlyne.git",
12
+ "directory": "packages/mcp-core"
13
+ },
14
+ "homepage": "https://github.com/dbydd/onlyne#readme",
15
+ "bugs": "https://github.com/dbydd/onlyne/issues",
16
+ "keywords": ["onlyne", "mcp", "model-context-protocol", "resource"],
17
+ "publishConfig": { "access": "public" },
18
+ "engines": { "bun": ">=1.4.3" },
19
+ "exports": {
20
+ ".": "./src/index.ts"
21
+ },
22
+ "files": ["src", "README.md", "LICENSE"],
23
+ "scripts": {
24
+ "check": "tsc --noEmit",
25
+ "test": "bun tests/verify.ts"
26
+ },
27
+ "dependencies": {
28
+ "@modelcontextprotocol/sdk": "^1.32.2",
29
+ "@onlyne/lib": "^3.0.0"
30
+ },
31
+ "devDependencies": {
32
+ "@types/bun": "^1.3.0",
33
+ "typescript": "^5.9.0"
34
+ }
35
+ }
package/src/index.ts ADDED
@@ -0,0 +1,198 @@
1
+ import type { Json, NodeId, Resource, ResourceDriver, ResourceRef } from '@onlyne/lib';
2
+ import { OnlyneError } from '@onlyne/lib';
3
+ import { Client } from '@modelcontextprotocol/sdk/client/index.js';
4
+ import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamablehttp.js';
5
+
6
+ export interface McpServerOptions {
7
+ name: string;
8
+ url: string;
9
+ /** Extra headers per request: Hindsight puts its API key here when enabled. */
10
+ headers?: Record<string, string>;
11
+ /** Per-request timeout for tool calls; the default matches the library's driver wait. */
12
+ timeoutMs?: number;
13
+ }
14
+
15
+ /** The result of one tool call, classified for the operation's three-way outcome (RFC 0015 §3). */
16
+ export type McpOutcome =
17
+ | { kind: 'result'; content?: Json; structuredContent?: Json }
18
+ | { kind: 'rejected'; text: string }
19
+ | { kind: 'unknown'; text: string };
20
+
21
+ const DEFAULT_TIMEOUT_MS = 30_000;
22
+ const wire = (value: object): Json => JSON.parse(JSON.stringify(value)) as Json;
23
+
24
+ /**
25
+ * One MCP server connection on the official SDK: `Client` over the streamable HTTP transport.
26
+ * The SDK owns the session id, the handshake, SSE parsing and the reconnect semantics; this
27
+ * class is only the façade the bridge and the gateway see.
28
+ */
29
+ export class McpConnection {
30
+ #client: Client | undefined;
31
+ readonly #options: McpServerOptions;
32
+ #tools: Array<{ name: string; description?: string; annotations?: { readOnlyHint?: boolean } }> = [];
33
+
34
+ constructor(options: McpServerOptions) {
35
+ this.#options = options;
36
+ }
37
+
38
+ get url(): string { return this.#options.url; }
39
+
40
+ get tools(): Array<{ name: string; description?: string; annotations?: { readOnlyHint?: boolean } }> { return this.#tools; }
41
+
42
+ /** Connects and reads the tool list; the SDK handles initialize and the session handshake. */
43
+ async start(): Promise<void> {
44
+ this.#tools = await this.refreshTools();
45
+ }
46
+
47
+ async refreshTools(): Promise<Array<{ name: string; description?: string; annotations?: { readOnlyHint?: boolean } }>> {
48
+ const client = await this.#ensureConnected();
49
+ const result = await client.listTools();
50
+ this.#tools = result.tools.map(tool => ({
51
+ name: tool.name,
52
+ ...(tool.description === undefined ? {} : { description: tool.description }),
53
+ ...(tool.annotations === undefined ? {} : { annotations: { readOnlyHint: tool.annotations.readOnlyHint } }),
54
+ }));
55
+ return this.#tools;
56
+ }
57
+
58
+ async call(name: string, arguments_: Json): Promise<McpOutcome> {
59
+ try {
60
+ const client = await this.#ensureConnected();
61
+ const result = await client.callTool({ name, arguments: arguments_ as Record<string, unknown> },
62
+ undefined, { resetTimeoutOnProgress: false, timeout: this.#options.timeoutMs ?? DEFAULT_TIMEOUT_MS });
63
+ if (result.isError === true) {
64
+ return { kind: 'rejected', text: textOf(result.content) };
65
+ }
66
+ return {
67
+ kind: 'result',
68
+ ...(result.content === undefined ? {} : { content: result.content as Json }),
69
+ ...(result.structuredContent === undefined ? {} : { structuredContent: result.structuredContent as Json }),
70
+ };
71
+ } catch (error) {
72
+ // A transport failure clears the client handle so the next call attempts a fresh handshake.
73
+ this.#client = undefined;
74
+ return { kind: 'unknown', text: error instanceof Error ? error.message : String(error) };
75
+ }
76
+ }
77
+
78
+ async close(): Promise<void> {
79
+ const client = this.#client;
80
+ this.#client = undefined;
81
+ if (client) await client.close().catch(() => undefined);
82
+ }
83
+
84
+ /** Reconnecting re-runs initialize, as RFC 0015 §5 requires; the SDK throws when offline. */
85
+ async #ensureConnected(): Promise<Client> {
86
+ if (this.#client !== undefined) return this.#client;
87
+ const transport = new StreamableHTTPClientTransport(new URL(this.#options.url), {
88
+ requestInit: { headers: this.#options.headers },
89
+ });
90
+ const client = new Client({ name: 'onlyne-mcp', version: '3.0.0' }, { capabilities: {} });
91
+ await client.connect(transport);
92
+ this.#client = client;
93
+ return client;
94
+ }
95
+ }
96
+
97
+ /** The resource clause one MCP server contributes: its id, operations and diagnostic data. */
98
+ export interface McpResourceDef {
99
+ resource_ref: ResourceRef;
100
+ operations: string[];
101
+ binding: { handler: NodeId; cursor: string };
102
+ log_readers: NodeId[];
103
+ data: Json;
104
+ }
105
+
106
+ /** Builds the Onlyne resource a server maps to (RFC 0015 §2: one server, one tool set). */
107
+ export function resourceOf(
108
+ owner: string,
109
+ server: McpServerOptions,
110
+ tools: ReadonlyArray<{ name: string; description?: string }>,
111
+ controllers: string[],
112
+ ): McpResourceDef {
113
+ return {
114
+ resource_ref: { owner, id: server.name },
115
+ operations: tools.map(tool => tool.name),
116
+ binding: { handler: owner, cursor: '0' },
117
+ log_readers: controllers.length > 0 ? controllers : [owner],
118
+ data: wire({
119
+ kind: 'mcp_server',
120
+ url: server.url,
121
+ tools: tools.map(tool => ({
122
+ name: tool.name,
123
+ ...(typeof tool.description === 'string' ? { description: tool.description.slice(0, 200) } : {}),
124
+ })),
125
+ ...(controllers.length > 0 ? {} : { note: 'owner only' }),
126
+ }),
127
+ };
128
+ }
129
+
130
+ /**
131
+ * The bridge from resource operations to `tools/call`. The tool list is pinned per server, so
132
+ * `validate` answers from the cache and a request for an unknown tool never leaves the node
133
+ * (RFC 0015 §2: `unsupported_delivery`, not sent).
134
+ */
135
+ export function createMcpBridge(servers: Array<{ server: McpServerOptions; connection: McpConnection }>): ResourceDriver {
136
+ const byServer = new Map(servers.map(entry => [entry.server.name, entry]));
137
+
138
+ function requireTool(ref: ResourceRef, operation: string): { entry: { server: McpServerOptions; connection: McpConnection }; tool: { name: string; annotations?: { readOnlyHint?: boolean } } } {
139
+ const entry = byServer.get(ref.id);
140
+ if (entry === undefined) {
141
+ throw new OnlyneError('invalid_request', `No MCP server serves the resource ${ref.id}.`);
142
+ }
143
+ const tool = entry.connection.tools.find(candidate => candidate.name === operation);
144
+ if (tool === undefined) {
145
+ throw new OnlyneError('unsupported_delivery', `The tool ${operation} is not in ${ref.id}'s tools/list.`);
146
+ }
147
+ return { entry, tool };
148
+ }
149
+
150
+ return {
151
+ async validate(resource: Resource, operation: string, data: Json | undefined): Promise<void> {
152
+ requireTool(resource.resource_ref, operation);
153
+ // `arguments` for `tools/call` is an object when present (RFC 0015 §2).
154
+ if (data !== undefined && (data === null || typeof data !== 'object' || Array.isArray(data))) {
155
+ throw new OnlyneError('invalid_request', `The arguments for ${operation} are an object.`);
156
+ }
157
+ },
158
+
159
+ async execute(resource: Resource, request): Promise<Omit<import('@onlyne/lib').OperationResult, 'operation_id'>> {
160
+ const { entry, tool } = requireTool(resource.resource_ref, request.operation);
161
+ const arguments_ = (request.data ?? {}) as Json;
162
+ const outcome = await entry.connection.call(request.operation, arguments_);
163
+ if (outcome.kind === 'unknown') {
164
+ // The transport never gave an answer: the call may or may not have run (RFC 0015 §3).
165
+ return { state: 'unknown', error: { code: 'unavailable', message: 'The MCP server gave no answer.', retryable: true, details: { source: outcome.text } } };
166
+ }
167
+ if (outcome.kind === 'rejected') {
168
+ // A read-only tool cannot have side effects, so its failure is a settled abort; a
169
+ // side-effecting tool's failure proves nothing about what it already did.
170
+ if (tool.annotations?.readOnlyHint === true) {
171
+ return { state: 'aborted', error: { code: 'unavailable', message: 'The tool reported failure.', retryable: false, details: { source: outcome.text } } };
172
+ }
173
+ return { state: 'unknown', error: { code: 'unavailable', message: 'The tool reported failure; the side effect is unconfirmed.', retryable: true, details: { source: outcome.text } } };
174
+ }
175
+ return {
176
+ state: 'committed',
177
+ data: wire({
178
+ ...(outcome.content === undefined ? {} : { content: outcome.content }),
179
+ ...(outcome.structuredContent === undefined ? {} : { structuredContent: outcome.structuredContent }),
180
+ }),
181
+ };
182
+ },
183
+ };
184
+ }
185
+
186
+ /** An error result's content is text blocks; their `text` fields are the readable message. */
187
+ function textOf(content: unknown): string {
188
+ if (typeof content === 'string') return content;
189
+ if (Array.isArray(content)) {
190
+ return content
191
+ .map(block => (typeof block === 'object' && block !== null && 'text' in block && typeof (block as { text?: unknown }).text === 'string'
192
+ ? (block as { text: string }).text
193
+ : ''))
194
+ .filter(text => text.length > 0)
195
+ .join('\n');
196
+ }
197
+ return JSON.stringify(content ?? '');
198
+ }