@kosha-ai/integration-mcp 0.0.0-stage → 0.4.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/LICENSE +21 -0
- package/README.md +10 -2
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +1 -0
- package/dist/lib/integration-mcp.d.ts +7 -0
- package/dist/lib/integration-mcp.d.ts.map +1 -0
- package/dist/lib/integration-mcp.js +368 -0
- package/docs/setup.md +34 -0
- package/migrations/001_init/migration.sql +62 -0
- package/package.json +53 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Codemancers
|
|
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,11 @@
|
|
|
1
|
-
#
|
|
1
|
+
# integration-mcp
|
|
2
2
|
|
|
3
|
-
This
|
|
3
|
+
This library was generated with [Nx](https://nx.dev).
|
|
4
|
+
|
|
5
|
+
## Building
|
|
6
|
+
|
|
7
|
+
Run `nx build integration-mcp` to build the library.
|
|
8
|
+
|
|
9
|
+
## Running unit tests
|
|
10
|
+
|
|
11
|
+
Run `nx test integration-mcp` to execute the unit tests via [Jest](https://jestjs.io).
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,GAAG,EACH,GAAG,IAAI,OAAO,EACd,iBAAiB,GAClB,MAAM,0BAA0B,CAAC"}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { mcp, mcp as default, McpDiscoveryError, } from './lib/integration-mcp.js';
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { KoshaIntegration } from '@kosha-ai/integration-sdk';
|
|
2
|
+
export declare class McpDiscoveryError extends Error {
|
|
3
|
+
constructor(message: string);
|
|
4
|
+
}
|
|
5
|
+
export declare function mcp(): KoshaIntegration;
|
|
6
|
+
export default mcp;
|
|
7
|
+
//# sourceMappingURL=integration-mcp.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"integration-mcp.d.ts","sourceRoot":"","sources":["../../src/lib/integration-mcp.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EAOV,gBAAgB,EAMjB,MAAM,2BAA2B,CAAC;AAInC,qBAAa,iBAAkB,SAAQ,KAAK;gBAC9B,OAAO,EAAE,MAAM;CAI5B;AAiZD,wBAAgB,GAAG,IAAI,gBAAgB,CAsFtC;AAED,eAAe,GAAG,CAAC"}
|
|
@@ -0,0 +1,368 @@
|
|
|
1
|
+
import { assertPublicUrl, defineIntegration, packageDirs, PrivateAddressError, s256Challenge, } from '@kosha-ai/integration-sdk';
|
|
2
|
+
const { docsPath, migrationsPath } = packageDirs(import.meta.url);
|
|
3
|
+
export class McpDiscoveryError extends Error {
|
|
4
|
+
constructor(message) {
|
|
5
|
+
super(message);
|
|
6
|
+
this.name = 'McpDiscoveryError';
|
|
7
|
+
}
|
|
8
|
+
}
|
|
9
|
+
/** Scopes worth asking for beyond the resource's own, when the server has them. */
|
|
10
|
+
const IDENTITY_SCOPES = ['openid', 'profile', 'email', 'offline_access'];
|
|
11
|
+
function required(value, what) {
|
|
12
|
+
if (typeof value !== 'string' || value.trim() === '') {
|
|
13
|
+
throw new McpDiscoveryError(`${what} is missing or not a string`);
|
|
14
|
+
}
|
|
15
|
+
return value;
|
|
16
|
+
}
|
|
17
|
+
const MAX_REDIRECTS = 5;
|
|
18
|
+
/**
|
|
19
|
+
* `fetch`, but every URL — the one as typed, and each hop a redirect sends
|
|
20
|
+
* it to — goes through `assertPublicUrl` first: `mcpUrl` is operator-entered,
|
|
21
|
+
* and the endpoints discovered from it are server-controlled, so a request
|
|
22
|
+
* here that followed an unchecked redirect could be steered anywhere,
|
|
23
|
+
* including cloud metadata (169.254.169.254).
|
|
24
|
+
*/
|
|
25
|
+
async function safeFetch(url, init) {
|
|
26
|
+
let target = await assertPublicUrl(url);
|
|
27
|
+
for (let redirects = 0;; redirects++) {
|
|
28
|
+
const response = await fetch(target.href, { ...init, redirect: 'manual' });
|
|
29
|
+
const location = response.headers.get('location');
|
|
30
|
+
if (response.status < 300 || response.status >= 400 || !location) {
|
|
31
|
+
return response;
|
|
32
|
+
}
|
|
33
|
+
if (redirects >= MAX_REDIRECTS) {
|
|
34
|
+
throw new McpDiscoveryError(`${target.href}: too many redirects`);
|
|
35
|
+
}
|
|
36
|
+
target = await assertPublicUrl(new URL(location, target).href);
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
async function fetchJson(url, init) {
|
|
40
|
+
const response = await safeFetch(url, {
|
|
41
|
+
...init,
|
|
42
|
+
headers: { Accept: 'application/json', ...init?.headers },
|
|
43
|
+
});
|
|
44
|
+
if (!response.ok) {
|
|
45
|
+
throw new McpDiscoveryError(`GET ${url} failed with ${response.status}`);
|
|
46
|
+
}
|
|
47
|
+
return (await response.json());
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* RFC 9728 §3.1: the metadata URL is formed by inserting a well-known path
|
|
51
|
+
* segment between the resource's host and its path component.
|
|
52
|
+
*/
|
|
53
|
+
function protectedResourceMetadataUrl(resourceUrl) {
|
|
54
|
+
const path = resourceUrl.pathname === '/' ? '' : resourceUrl.pathname;
|
|
55
|
+
return `${resourceUrl.origin}/.well-known/oauth-protected-resource${path}`;
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Finds the resource's authorization server(s). Tries the RFC 9728 metadata
|
|
59
|
+
* URL first; if the server never implemented resource metadata (common for
|
|
60
|
+
* MCP servers that are their own authorization server), falls back to
|
|
61
|
+
* treating the resource's own origin as the issuer.
|
|
62
|
+
*/
|
|
63
|
+
async function discoverProtectedResource(mcpUrl) {
|
|
64
|
+
try {
|
|
65
|
+
return await fetchJson(protectedResourceMetadataUrl(mcpUrl));
|
|
66
|
+
}
|
|
67
|
+
catch (error) {
|
|
68
|
+
if (error instanceof PrivateAddressError)
|
|
69
|
+
throw error;
|
|
70
|
+
return { authorization_servers: [mcpUrl.origin], resource: mcpUrl.href };
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* RFC 8414 §3.1: the metadata URL inserts the well-known segment before the
|
|
75
|
+
* issuer's own path, so `https://host/auth` resolves to
|
|
76
|
+
* `https://host/.well-known/oauth-authorization-server/auth`. Servers
|
|
77
|
+
* disagree on this, so three shapes are tried in order: the RFC-correct
|
|
78
|
+
* path-insertion form, the well-known segment simply appended to the issuer,
|
|
79
|
+
* and finally OpenID Connect discovery (a superset of the fields this needs).
|
|
80
|
+
*/
|
|
81
|
+
async function discoverAuthorizationServer(issuer) {
|
|
82
|
+
const url = new URL(issuer);
|
|
83
|
+
const path = url.pathname === '/' ? '' : url.pathname;
|
|
84
|
+
const candidates = [
|
|
85
|
+
`${url.origin}/.well-known/oauth-authorization-server${path}`,
|
|
86
|
+
`${issuer.replace(/\/$/, '')}/.well-known/oauth-authorization-server`,
|
|
87
|
+
`${url.origin}/.well-known/openid-configuration${path}`,
|
|
88
|
+
`${issuer.replace(/\/$/, '')}/.well-known/openid-configuration`,
|
|
89
|
+
];
|
|
90
|
+
let lastError;
|
|
91
|
+
for (const candidate of candidates) {
|
|
92
|
+
try {
|
|
93
|
+
return await fetchJson(candidate);
|
|
94
|
+
}
|
|
95
|
+
catch (error) {
|
|
96
|
+
if (error instanceof PrivateAddressError)
|
|
97
|
+
throw error;
|
|
98
|
+
lastError = error;
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
throw new McpDiscoveryError(`Could not discover OAuth endpoints for ${issuer}: ${lastError instanceof Error ? lastError.message : String(lastError)}`);
|
|
102
|
+
}
|
|
103
|
+
/** RFC 7591 §3.1: dynamic client registration. */
|
|
104
|
+
async function registerClient(registrationEndpoint, args) {
|
|
105
|
+
const response = await safeFetch(registrationEndpoint, {
|
|
106
|
+
method: 'POST',
|
|
107
|
+
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
|
|
108
|
+
body: JSON.stringify({
|
|
109
|
+
client_name: 'Kosha',
|
|
110
|
+
redirect_uris: [args.redirectUri],
|
|
111
|
+
grant_types: ['authorization_code', 'refresh_token'],
|
|
112
|
+
response_types: ['code'],
|
|
113
|
+
// No client secret kept anywhere an end user could see it, and MCP's
|
|
114
|
+
// installed-client model has nowhere safe to keep one anyway.
|
|
115
|
+
token_endpoint_auth_method: 'none',
|
|
116
|
+
...(args.scopes.length > 0 ? { scope: args.scopes.join(' ') } : {}),
|
|
117
|
+
}),
|
|
118
|
+
});
|
|
119
|
+
const body = (await response.json().catch(() => null));
|
|
120
|
+
if (!response.ok || !body?.['client_id']) {
|
|
121
|
+
throw new McpDiscoveryError(`Dynamic client registration at ${registrationEndpoint} failed with ${response.status}`);
|
|
122
|
+
}
|
|
123
|
+
return body;
|
|
124
|
+
}
|
|
125
|
+
/**
|
|
126
|
+
* Any MCP server that authenticates with OAuth2.
|
|
127
|
+
*
|
|
128
|
+
* Unlike Asana or GitHub, there is no one fixed server or OAuth app: the
|
|
129
|
+
* operator types the server's URL into the configuration, and Kosha
|
|
130
|
+
* discovers its authorization endpoints (RFC 9728, RFC 8414) and registers
|
|
131
|
+
* itself as a client (RFC 7591) the first time anyone connects — see
|
|
132
|
+
* `prepareClient` below. The discovered endpoints and the issued client
|
|
133
|
+
* credentials are then persisted onto the configuration's own columns
|
|
134
|
+
* (declared via `configFields`, created by this package's migration), so
|
|
135
|
+
* later connects and token refreshes reuse them instead of registering a new
|
|
136
|
+
* client every time.
|
|
137
|
+
*/
|
|
138
|
+
function mcpUrlOf(fields) {
|
|
139
|
+
return new URL(required(fields['mcpUrl'], 'mcpUrl'));
|
|
140
|
+
}
|
|
141
|
+
const auth = {
|
|
142
|
+
type: 'OAUTH2',
|
|
143
|
+
// The provider's own scope catalogue is not knowable until an operator
|
|
144
|
+
// supplies a URL; `prepareClient` discovers it per configuration and
|
|
145
|
+
// stores it in `scopesSupported`, which `buildAuthorizationUrl` reads.
|
|
146
|
+
scopesAvailable: [],
|
|
147
|
+
scopesRequested: [],
|
|
148
|
+
pkce: true,
|
|
149
|
+
// There is no OAuth app for an operator to register: `prepareClient`
|
|
150
|
+
// obtains a client id (and secret, where the server issues one) itself.
|
|
151
|
+
requiresClientCredentials: false,
|
|
152
|
+
async prepareClient({ fields, redirectUri, }) {
|
|
153
|
+
// Already discovered by an earlier connect; nothing new to persist.
|
|
154
|
+
if (fields['tokenEndpoint'] && fields['authorizationEndpoint'])
|
|
155
|
+
return;
|
|
156
|
+
const mcpUrl = mcpUrlOf(fields);
|
|
157
|
+
const resourceMetadata = await discoverProtectedResource(mcpUrl);
|
|
158
|
+
const issuer = resourceMetadata.authorization_servers?.[0];
|
|
159
|
+
if (!issuer) {
|
|
160
|
+
throw new McpDiscoveryError(`${mcpUrl.href} named no authorization server`);
|
|
161
|
+
}
|
|
162
|
+
const serverMetadata = await discoverAuthorizationServer(issuer);
|
|
163
|
+
const authorizationEndpoint = required(serverMetadata.authorization_endpoint, 'authorization_endpoint');
|
|
164
|
+
const tokenEndpoint = required(serverMetadata.token_endpoint, 'token_endpoint');
|
|
165
|
+
// The resource's own scopes, plus only the identity-related ones the
|
|
166
|
+
// server advertises — not its whole catalogue, which may cover things
|
|
167
|
+
// unrelated to this resource.
|
|
168
|
+
const serverScopes = serverMetadata.scopes_supported ?? [];
|
|
169
|
+
const resourceScopes = resourceMetadata.scopes_supported ?? [];
|
|
170
|
+
const scopes = [
|
|
171
|
+
...new Set([
|
|
172
|
+
...(resourceScopes.length > 0 ? resourceScopes : serverScopes),
|
|
173
|
+
...IDENTITY_SCOPES.filter((scope) => serverScopes.includes(scope)),
|
|
174
|
+
]),
|
|
175
|
+
];
|
|
176
|
+
if (!serverMetadata.registration_endpoint) {
|
|
177
|
+
throw new McpDiscoveryError(`${issuer} does not support dynamic client registration (RFC 7591); ` +
|
|
178
|
+
'it must be pre-registered, which Kosha does not yet support.');
|
|
179
|
+
}
|
|
180
|
+
const registration = await registerClient(serverMetadata.registration_endpoint, { redirectUri, scopes });
|
|
181
|
+
return {
|
|
182
|
+
fields: {
|
|
183
|
+
authorizationEndpoint,
|
|
184
|
+
tokenEndpoint,
|
|
185
|
+
registrationEndpoint: serverMetadata.registration_endpoint,
|
|
186
|
+
userinfoEndpoint: serverMetadata.userinfo_endpoint ?? null,
|
|
187
|
+
scopesSupported: scopes.join(' '),
|
|
188
|
+
resource: resourceMetadata.resource ?? mcpUrl.href,
|
|
189
|
+
},
|
|
190
|
+
credentials: {
|
|
191
|
+
clientId: required(registration.client_id, 'client_id'),
|
|
192
|
+
...(registration.client_secret
|
|
193
|
+
? { clientSecret: registration.client_secret }
|
|
194
|
+
: {}),
|
|
195
|
+
},
|
|
196
|
+
};
|
|
197
|
+
},
|
|
198
|
+
buildAuthorizationUrl({ client, state, codeVerifier, }) {
|
|
199
|
+
const url = new URL(required(client.fields['authorizationEndpoint'], 'authorizationEndpoint'));
|
|
200
|
+
url.searchParams.set('response_type', 'code');
|
|
201
|
+
url.searchParams.set('client_id', client.clientId);
|
|
202
|
+
url.searchParams.set('redirect_uri', client.redirectUri);
|
|
203
|
+
url.searchParams.set('state', state);
|
|
204
|
+
const scope = client.fields['scopesSupported'];
|
|
205
|
+
if (typeof scope === 'string' && scope.length > 0) {
|
|
206
|
+
url.searchParams.set('scope', scope);
|
|
207
|
+
}
|
|
208
|
+
const resource = client.fields['resource'];
|
|
209
|
+
if (typeof resource === 'string') {
|
|
210
|
+
url.searchParams.set('resource', resource);
|
|
211
|
+
}
|
|
212
|
+
if (!codeVerifier) {
|
|
213
|
+
throw new McpDiscoveryError('PKCE verifier missing for MCP connect');
|
|
214
|
+
}
|
|
215
|
+
url.searchParams.set('code_challenge', s256Challenge(codeVerifier));
|
|
216
|
+
url.searchParams.set('code_challenge_method', 'S256');
|
|
217
|
+
return url.toString();
|
|
218
|
+
},
|
|
219
|
+
async exchangeCode({ client, code, codeVerifier, }) {
|
|
220
|
+
return postToken(client, {
|
|
221
|
+
grant_type: 'authorization_code',
|
|
222
|
+
code,
|
|
223
|
+
redirect_uri: client.redirectUri,
|
|
224
|
+
...(codeVerifier ? { code_verifier: codeVerifier } : {}),
|
|
225
|
+
});
|
|
226
|
+
},
|
|
227
|
+
async refresh({ client, refreshToken }) {
|
|
228
|
+
return postToken(client, {
|
|
229
|
+
grant_type: 'refresh_token',
|
|
230
|
+
refresh_token: refreshToken,
|
|
231
|
+
});
|
|
232
|
+
},
|
|
233
|
+
};
|
|
234
|
+
/**
|
|
235
|
+
* The token request both `exchangeCode` and `refresh` make, differing only in
|
|
236
|
+
* the grant-specific parameters. `client_secret` is sent only when the
|
|
237
|
+
* server issued one at registration — most MCP clients are public clients
|
|
238
|
+
* (`token_endpoint_auth_method: 'none'`), and sending an empty secret can
|
|
239
|
+
* make a strict server treat the request as a confidential client's.
|
|
240
|
+
*/
|
|
241
|
+
async function postToken(client, grantParams) {
|
|
242
|
+
const tokenEndpoint = required(client.fields['tokenEndpoint'], 'tokenEndpoint');
|
|
243
|
+
const resource = client.fields['resource'];
|
|
244
|
+
const params = {
|
|
245
|
+
client_id: client.clientId,
|
|
246
|
+
...(client.clientSecret ? { client_secret: client.clientSecret } : {}),
|
|
247
|
+
...(typeof resource === 'string' ? { resource } : {}),
|
|
248
|
+
...grantParams,
|
|
249
|
+
};
|
|
250
|
+
const response = await safeFetch(tokenEndpoint, {
|
|
251
|
+
method: 'POST',
|
|
252
|
+
headers: {
|
|
253
|
+
Accept: 'application/json',
|
|
254
|
+
'Content-Type': 'application/x-www-form-urlencoded',
|
|
255
|
+
},
|
|
256
|
+
body: new URLSearchParams(params).toString(),
|
|
257
|
+
});
|
|
258
|
+
const body = (await response.json().catch(() => null));
|
|
259
|
+
if (!response.ok || !body || body['error']) {
|
|
260
|
+
const detail = body?.['error_description'] ??
|
|
261
|
+
body?.['error'] ??
|
|
262
|
+
`HTTP ${response.status}`;
|
|
263
|
+
throw new McpDiscoveryError(`Token request to ${tokenEndpoint} failed: ${detail}`);
|
|
264
|
+
}
|
|
265
|
+
const accessToken = body['access_token'];
|
|
266
|
+
if (typeof accessToken !== 'string') {
|
|
267
|
+
throw new McpDiscoveryError('Token response contained no access_token');
|
|
268
|
+
}
|
|
269
|
+
return {
|
|
270
|
+
accessToken,
|
|
271
|
+
refreshToken: typeof body['refresh_token'] === 'string'
|
|
272
|
+
? body['refresh_token']
|
|
273
|
+
: undefined,
|
|
274
|
+
tokenType: typeof body['token_type'] === 'string' ? body['token_type'] : undefined,
|
|
275
|
+
expiresInSeconds: typeof body['expires_in'] === 'number' ? body['expires_in'] : undefined,
|
|
276
|
+
scope: typeof body['scope'] === 'string' ? body['scope'] : undefined,
|
|
277
|
+
raw: body,
|
|
278
|
+
};
|
|
279
|
+
}
|
|
280
|
+
/**
|
|
281
|
+
* Reads a JWT's claims without verifying its signature. Safe here
|
|
282
|
+
* specifically because the token just came back over TLS from the server's
|
|
283
|
+
* own token endpoint (see `postToken`) — nothing untrusted handed it to us.
|
|
284
|
+
* Returns `null` for an opaque (non-JWT) token or an undecodable payload.
|
|
285
|
+
*/
|
|
286
|
+
function decodeJwtPayload(token) {
|
|
287
|
+
const parts = token.split('.');
|
|
288
|
+
if (parts.length !== 3)
|
|
289
|
+
return null;
|
|
290
|
+
try {
|
|
291
|
+
const payload = JSON.parse(Buffer.from(parts[1], 'base64url').toString('utf8'));
|
|
292
|
+
return payload && typeof payload === 'object' ? payload : null;
|
|
293
|
+
}
|
|
294
|
+
catch {
|
|
295
|
+
return null;
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
export function mcp() {
|
|
299
|
+
return defineIntegration({
|
|
300
|
+
key: 'mcp',
|
|
301
|
+
name: 'MCP',
|
|
302
|
+
docsPath,
|
|
303
|
+
migrationsPath,
|
|
304
|
+
auth,
|
|
305
|
+
configFields: [
|
|
306
|
+
{
|
|
307
|
+
key: 'mcpUrl',
|
|
308
|
+
label: 'MCP Server URL',
|
|
309
|
+
type: 'string',
|
|
310
|
+
required: true,
|
|
311
|
+
help: 'The MCP server to connect to, e.g. https://example.com/mcp. Kosha discovers its OAuth endpoints and registers itself as a client automatically — nothing to register by hand.',
|
|
312
|
+
},
|
|
313
|
+
],
|
|
314
|
+
api: {
|
|
315
|
+
resolveBaseUrl: ({ fields }) => {
|
|
316
|
+
const mcpUrl = fields?.['mcpUrl'];
|
|
317
|
+
return typeof mcpUrl === 'string' ? mcpUrl : undefined;
|
|
318
|
+
},
|
|
319
|
+
authHeaders: ({ accessToken }) => ({
|
|
320
|
+
Authorization: `Bearer ${accessToken}`,
|
|
321
|
+
}),
|
|
322
|
+
// No egress rule: the host is whatever URL the operator entered, so
|
|
323
|
+
// there is no fixed hostname to declare here. This means a sandbox
|
|
324
|
+
// cannot yet borrow an MCP connection's identity via the egress broker.
|
|
325
|
+
},
|
|
326
|
+
identity: {
|
|
327
|
+
async fetchAccount({ accessToken, fields, }) {
|
|
328
|
+
// Namespaced by server, since the same MCP user id could otherwise
|
|
329
|
+
// collide across two unrelated servers sharing this integration.
|
|
330
|
+
const namespace = (typeof fields?.['resource'] === 'string' && fields['resource']) ||
|
|
331
|
+
mcpUrlOf(fields ?? {}).href;
|
|
332
|
+
// Enrichment, not a dependency — fall back rather than fail the
|
|
333
|
+
// connection if the server refuses or fails this call.
|
|
334
|
+
const userinfoEndpoint = fields?.['userinfoEndpoint'];
|
|
335
|
+
if (typeof userinfoEndpoint === 'string' && userinfoEndpoint) {
|
|
336
|
+
try {
|
|
337
|
+
const user = await fetchJson(userinfoEndpoint, {
|
|
338
|
+
headers: { Authorization: `Bearer ${accessToken}` },
|
|
339
|
+
});
|
|
340
|
+
const subject = user.sub ?? user.email;
|
|
341
|
+
if (subject) {
|
|
342
|
+
return {
|
|
343
|
+
externalAccountId: `${namespace}:${subject}`,
|
|
344
|
+
label: user.name ?? user.email ?? subject,
|
|
345
|
+
};
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
catch {
|
|
349
|
+
// Fall through to the claims already on the access token.
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
// Fall back to the access token's own `sub` claim, when it has one.
|
|
353
|
+
const claims = decodeJwtPayload(accessToken);
|
|
354
|
+
const sub = claims && typeof claims['sub'] === 'string' ? claims['sub'] : null;
|
|
355
|
+
if (sub) {
|
|
356
|
+
return { externalAccountId: `${namespace}:${sub}`, label: sub };
|
|
357
|
+
}
|
|
358
|
+
// No per-user id anywhere: failing is safer than a shared fallback
|
|
359
|
+
// (e.g. the hostname) that would merge every end user into one
|
|
360
|
+
// connection.
|
|
361
|
+
throw new McpDiscoveryError(`${namespace} named no account for this token: it issued an ` +
|
|
362
|
+
'opaque access token and has no OIDC userinfo endpoint, so ' +
|
|
363
|
+
'Kosha has no per-user identifier to connect with.');
|
|
364
|
+
},
|
|
365
|
+
},
|
|
366
|
+
});
|
|
367
|
+
}
|
|
368
|
+
export default mcp;
|
package/docs/setup.md
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
# MCP Setup
|
|
2
|
+
|
|
3
|
+
Unlike the other integrations, there is no fixed MCP server and no OAuth app
|
|
4
|
+
to register. Give Kosha the URL of any MCP server that authenticates with
|
|
5
|
+
OAuth, and Kosha discovers its authorization endpoints and registers itself
|
|
6
|
+
as a client automatically, the first time anyone connects.
|
|
7
|
+
|
|
8
|
+
## 1. Create the configuration
|
|
9
|
+
|
|
10
|
+
Pick **MCP** as the provider and enter the server's URL, e.g.
|
|
11
|
+
`https://example.com/mcp`. Leave client ID and secret blank — there is
|
|
12
|
+
nothing to put there.
|
|
13
|
+
|
|
14
|
+
## 2. Connect
|
|
15
|
+
|
|
16
|
+
Start a connect session as usual. On the first connect, Kosha:
|
|
17
|
+
|
|
18
|
+
1. Fetches `/.well-known/oauth-protected-resource` (or, failing that, treats
|
|
19
|
+
the server's own origin as its authorization server) to find which
|
|
20
|
+
authorization server issues tokens for it.
|
|
21
|
+
2. Fetches that authorization server's metadata
|
|
22
|
+
(`/.well-known/oauth-authorization-server` or
|
|
23
|
+
`/.well-known/openid-configuration`) for its authorize, token, and
|
|
24
|
+
registration endpoints.
|
|
25
|
+
3. Registers itself as an OAuth client at the registration endpoint (RFC 7591) and stores the issued client ID (and secret, if the server issues
|
|
26
|
+
one) alongside the discovered endpoints on the configuration.
|
|
27
|
+
|
|
28
|
+
Later connects and token refreshes reuse what was discovered the first time.
|
|
29
|
+
|
|
30
|
+
## Requirements
|
|
31
|
+
|
|
32
|
+
The MCP server must support dynamic client registration (RFC 7591). A server
|
|
33
|
+
with a fixed, manually-registered OAuth app is not yet supported — connecting
|
|
34
|
+
fails with a clear error naming which step failed, rather than guessing.
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
CREATE TABLE "mcp_configuration" (
|
|
2
|
+
"id" TEXT NOT NULL,
|
|
3
|
+
"environmentId" TEXT NOT NULL,
|
|
4
|
+
"name" TEXT NOT NULL,
|
|
5
|
+
"slug" TEXT NOT NULL,
|
|
6
|
+
-- Encrypted, so TEXT rather than JSONB. Holds the client id (and secret,
|
|
7
|
+
-- where the server issues one) obtained via dynamic client registration,
|
|
8
|
+
-- not anything an operator supplied.
|
|
9
|
+
"credentials" TEXT,
|
|
10
|
+
-- Operator-supplied: the only thing there is to configure before Kosha
|
|
11
|
+
-- discovers the rest.
|
|
12
|
+
"mcpUrl" TEXT NOT NULL,
|
|
13
|
+
-- Everything below is discovered by `prepareClient` (RFC 9728 / RFC 8414)
|
|
14
|
+
-- the first time anyone connects, and persisted here so a later connect
|
|
15
|
+
-- or token refresh does not discover or register a client again.
|
|
16
|
+
"authorizationEndpoint" TEXT,
|
|
17
|
+
"tokenEndpoint" TEXT,
|
|
18
|
+
"registrationEndpoint" TEXT,
|
|
19
|
+
"userinfoEndpoint" TEXT,
|
|
20
|
+
"scopesSupported" TEXT,
|
|
21
|
+
"resource" TEXT,
|
|
22
|
+
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
|
23
|
+
"updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
|
24
|
+
|
|
25
|
+
CONSTRAINT "mcp_configuration_pkey" PRIMARY KEY ("id")
|
|
26
|
+
);
|
|
27
|
+
|
|
28
|
+
CREATE TABLE "mcp_connection" (
|
|
29
|
+
"accountId" TEXT NOT NULL,
|
|
30
|
+
-- Copied from `account` so the unique index below can use it.
|
|
31
|
+
"userId" TEXT NOT NULL,
|
|
32
|
+
"environmentId" TEXT NOT NULL,
|
|
33
|
+
"configurationId" TEXT NOT NULL,
|
|
34
|
+
"metadata" JSONB,
|
|
35
|
+
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
|
36
|
+
"updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
|
37
|
+
|
|
38
|
+
CONSTRAINT "mcp_connection_pkey" PRIMARY KEY ("accountId")
|
|
39
|
+
);
|
|
40
|
+
|
|
41
|
+
CREATE UNIQUE INDEX "mcp_configuration_environmentId_slug_key" ON "mcp_configuration"("environmentId", "slug");
|
|
42
|
+
|
|
43
|
+
CREATE INDEX "mcp_configuration_environmentId_idx" ON "mcp_configuration"("environmentId");
|
|
44
|
+
|
|
45
|
+
CREATE UNIQUE INDEX "mcp_connection_environmentId_configurationId_userId_key" ON "mcp_connection"("environmentId", "configurationId", "userId");
|
|
46
|
+
|
|
47
|
+
CREATE INDEX "mcp_connection_environmentId_idx" ON "mcp_connection"("environmentId");
|
|
48
|
+
|
|
49
|
+
CREATE INDEX "mcp_connection_configurationId_idx" ON "mcp_connection"("configurationId");
|
|
50
|
+
|
|
51
|
+
CREATE INDEX "mcp_connection_userId_idx" ON "mcp_connection"("userId");
|
|
52
|
+
|
|
53
|
+
ALTER TABLE "mcp_configuration" ADD CONSTRAINT "mcp_configuration_environmentId_fkey" FOREIGN KEY ("environmentId") REFERENCES "environment"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
|
54
|
+
|
|
55
|
+
ALTER TABLE "mcp_connection" ADD CONSTRAINT "mcp_connection_accountId_fkey" FOREIGN KEY ("accountId") REFERENCES "account"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
|
56
|
+
|
|
57
|
+
ALTER TABLE "mcp_connection" ADD CONSTRAINT "mcp_connection_userId_fkey" FOREIGN KEY ("userId") REFERENCES "user"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
|
58
|
+
|
|
59
|
+
ALTER TABLE "mcp_connection" ADD CONSTRAINT "mcp_connection_environmentId_fkey" FOREIGN KEY ("environmentId") REFERENCES "environment"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
|
60
|
+
|
|
61
|
+
-- RESTRICT: a configuration that still has connections cannot be deleted.
|
|
62
|
+
ALTER TABLE "mcp_connection" ADD CONSTRAINT "mcp_connection_configurationId_fkey" FOREIGN KEY ("configurationId") REFERENCES "mcp_configuration"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
package/package.json
CHANGED
|
@@ -1,6 +1,56 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kosha-ai/integration-mcp",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.4.0",
|
|
4
|
+
"description": "MCP (Model Context Protocol) server integration for Kosha",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"kosha",
|
|
7
|
+
"mcp",
|
|
8
|
+
"oauth",
|
|
9
|
+
"integrations"
|
|
10
|
+
],
|
|
11
|
+
"license": "MIT",
|
|
12
|
+
"homepage": "https://github.com/codemancers/kosha#readme",
|
|
13
|
+
"bugs": {
|
|
14
|
+
"url": "https://github.com/codemancers/kosha/issues"
|
|
15
|
+
},
|
|
16
|
+
"repository": {
|
|
17
|
+
"type": "git",
|
|
18
|
+
"url": "git+https://github.com/codemancers/kosha.git",
|
|
19
|
+
"directory": "packages/integrations/mcp"
|
|
20
|
+
},
|
|
21
|
+
"publishConfig": {
|
|
22
|
+
"access": "public"
|
|
23
|
+
},
|
|
24
|
+
"type": "module",
|
|
25
|
+
"main": "./dist/index.js",
|
|
26
|
+
"module": "./dist/index.js",
|
|
27
|
+
"types": "./dist/index.d.ts",
|
|
28
|
+
"exports": {
|
|
29
|
+
"./package.json": "./package.json",
|
|
30
|
+
".": {
|
|
31
|
+
"@org/source": "./src/index.ts",
|
|
32
|
+
"types": "./dist/index.d.ts",
|
|
33
|
+
"import": "./dist/index.js",
|
|
34
|
+
"default": "./dist/index.js"
|
|
35
|
+
}
|
|
36
|
+
},
|
|
37
|
+
"files": [
|
|
38
|
+
"dist",
|
|
39
|
+
"docs",
|
|
40
|
+
"migrations",
|
|
41
|
+
"!**/*.tsbuildinfo"
|
|
42
|
+
],
|
|
43
|
+
"dependencies": {
|
|
44
|
+
"tslib": "^2.3.0"
|
|
45
|
+
},
|
|
46
|
+
"kosha": {
|
|
47
|
+
"kind": "integration",
|
|
48
|
+
"key": "mcp"
|
|
49
|
+
},
|
|
50
|
+
"peerDependencies": {
|
|
51
|
+
"@kosha-ai/integration-sdk": "0.4.0"
|
|
52
|
+
},
|
|
53
|
+
"devDependencies": {
|
|
54
|
+
"@kosha-ai/integration-sdk": "0.4.0"
|
|
55
|
+
}
|
|
6
56
|
}
|