@aventara/mcp 0.0.0-stage → 1.0.0-rc.1
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/CHANGELOG.md +25 -0
- package/LICENSE +91 -0
- package/LICENSE-ADDITIONAL-PERMISSION.md +9 -0
- package/README.md +144 -2
- package/dist/av-mcp.d.ts +5 -0
- package/dist/av-mcp.js +1 -0
- package/dist/endpoint-access.policy.d.ts +33 -0
- package/dist/endpoint-access.policy.js +89 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.js +1 -0
- package/dist/json-text.writer.d.ts +7 -0
- package/dist/json-text.writer.js +44 -0
- package/dist/mcp.binder.d.ts +73 -0
- package/dist/mcp.binder.js +256 -0
- package/dist/tool-call.translator.d.ts +32 -0
- package/dist/tool-call.translator.js +169 -0
- package/dist/tool-catalog.compiler.d.ts +44 -0
- package/dist/tool-catalog.compiler.js +210 -0
- package/dist/tool-result.encoder.d.ts +27 -0
- package/dist/tool-result.encoder.js +29 -0
- package/package.json +38 -3
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
# @aventara/mcp
|
|
2
|
+
|
|
3
|
+
## 1.0.0-rc.1
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- New package: the MCP server of an Aventara application. With `mcp` in the configuration, `@aventara/nest` mounts it
|
|
8
|
+
at that path over the Streamable HTTP transport, stateless. Its tools are the operation families the `agent` layer
|
|
9
|
+
exposes (`find`, `create`, `update`, `delete`, `upsert`) and `transaction`, each taking `{ resource, variant, args }`
|
|
10
|
+
(`transaction`: `{ steps }`, with `$ref` between steps). Every call runs as the `agent` origin through the protocol's
|
|
11
|
+
own decoding and validation; a success answers the envelope as structured content, a failure an MCP tool error
|
|
12
|
+
carrying the envelope and its issues. The Agent Contract is the resource `aventara://contract`.
|
|
13
|
+
- With `mcp.authorization`, the endpoint is an OAuth 2.1 protected resource: it publishes its metadata at
|
|
14
|
+
`/.well-known/oauth-protected-resource` plus the endpoint's path, answers a request without a good bearer token `401`
|
|
15
|
+
with a `WWW-Authenticate` challenge, and puts what `verify` returned into `ctx.$state.mcp.claims`. Without it, the
|
|
16
|
+
endpoint answers callers on the same machine only.
|
|
17
|
+
- A failure of the endpoint itself (the MCP SDK's server or transport) is answered `500` with no detail and reported to
|
|
18
|
+
the Framework's diagnostics sink as an `AvMcpDiagnostic`, so the raw error is not lost.
|
|
19
|
+
- A throw inside a tool or resource handler no longer reaches the agent with its raw message. A tool call answers the
|
|
20
|
+
generic `A3000` envelope as a tool error (`isError: true`), the form the protocol's own `A3000` takes; a resource or
|
|
21
|
+
list request answers a JSON-RPC internal error with the same generic message. The raw error goes to the diagnostics
|
|
22
|
+
sink as an `AvMcpDiagnostic`.
|
|
23
|
+
- A tool call's arguments nested deeper than the protocol allows are refused as the protocol refuses them from a
|
|
24
|
+
client (`A2009` with `V1013`, or `V1021` for a `json` value, at the arguments' path), as a tool error. The server
|
|
25
|
+
writes the arguments on without recursing on their depth, so a deep value no longer overflows the stack.
|
package/LICENSE
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
Required Notice: Copyright 2026 Mohamed Ragheb
|
|
2
|
+
|
|
3
|
+
# PolyForm Shield License 1.0.0
|
|
4
|
+
|
|
5
|
+
<https://polyformproject.org/licenses/shield/1.0.0>
|
|
6
|
+
|
|
7
|
+
## Acceptance
|
|
8
|
+
|
|
9
|
+
In order to get any license under these terms, you must agree to them as both strict obligations and conditions to all your licenses.
|
|
10
|
+
|
|
11
|
+
## Copyright License
|
|
12
|
+
|
|
13
|
+
The licensor grants you a copyright license for the software to do everything you might do with the software that would otherwise infringe the licensor's copyright in it for any permitted purpose. However, you may only distribute the software according to [Distribution License](#distribution-license) and make changes or new works based on the software according to [Changes and New Works License](#changes-and-new-works-license).
|
|
14
|
+
|
|
15
|
+
## Distribution License
|
|
16
|
+
|
|
17
|
+
The licensor grants you an additional copyright license to distribute copies of the software. Your license to distribute covers distributing the software with changes and new works permitted by [Changes and New Works License](#changes-and-new-works-license).
|
|
18
|
+
|
|
19
|
+
## Notices
|
|
20
|
+
|
|
21
|
+
You must ensure that anyone who gets a copy of any part of the software from you also gets a copy of these terms or the URL for them above, as well as copies of any plain-text lines beginning with `Required Notice:` that the licensor provided with the software. For example:
|
|
22
|
+
|
|
23
|
+
> Required Notice: Copyright Yoyodyne, Inc. (http://example.com)
|
|
24
|
+
|
|
25
|
+
## Changes and New Works License
|
|
26
|
+
|
|
27
|
+
The licensor grants you an additional copyright license to make changes and new works based on the software for any permitted purpose.
|
|
28
|
+
|
|
29
|
+
## Patent License
|
|
30
|
+
|
|
31
|
+
The licensor grants you a patent license for the software that covers patent claims the licensor can license, or becomes able to license, that you would infringe by using the software.
|
|
32
|
+
|
|
33
|
+
## Noncompete
|
|
34
|
+
|
|
35
|
+
Any purpose is a permitted purpose, except for providing any product that competes with the software or any product the licensor or any of its affiliates provides using the software.
|
|
36
|
+
|
|
37
|
+
## Competition
|
|
38
|
+
|
|
39
|
+
Goods and services compete even when they provide functionality through different kinds of interfaces or for different technical platforms. Applications can compete with services, libraries with plugins, frameworks with development tools, and so on, even if they're written in different programming languages or for different computer architectures. Goods and services compete even when provided free of charge. If you market a product as a practical substitute for the software or another product, it definitely competes.
|
|
40
|
+
|
|
41
|
+
## New Products
|
|
42
|
+
|
|
43
|
+
If you are using the software to provide a product that does not compete, but the licensor or any of its affiliates brings your product into competition by providing a new version of the software or another product using the software, you may continue using versions of the software available under these terms beforehand to provide your competing product, but not any later versions.
|
|
44
|
+
|
|
45
|
+
## Discontinued Products
|
|
46
|
+
|
|
47
|
+
You may begin using the software to compete with a product or service that the licensor or any of its affiliates has stopped providing, unless the licensor includes a plain-text line beginning with `Licensor Line of Business:` with the software that mentions that line of business. For example:
|
|
48
|
+
|
|
49
|
+
> Licensor Line of Business: YoyodyneCMS Content Management System (http://example.com/cms)
|
|
50
|
+
|
|
51
|
+
## Sales of Business
|
|
52
|
+
|
|
53
|
+
If the licensor or any of its affiliates sells a line of business developing the software or using the software to provide a product, the buyer can also enforce [Noncompete](#noncompete) for that product.
|
|
54
|
+
|
|
55
|
+
## Fair Use
|
|
56
|
+
|
|
57
|
+
You may have "fair use" rights for the software under the law. These terms do not limit them.
|
|
58
|
+
|
|
59
|
+
## No Other Rights
|
|
60
|
+
|
|
61
|
+
These terms do not allow you to sublicense or transfer any of your licenses to anyone else, or prevent the licensor from granting licenses to anyone else. These terms do not imply any other licenses.
|
|
62
|
+
|
|
63
|
+
## Patent Defense
|
|
64
|
+
|
|
65
|
+
If you make any written claim that the software infringes or contributes to infringement of any patent, your patent license for the software granted under these terms ends immediately. If your company makes such a claim, your patent license ends immediately for work on behalf of your company.
|
|
66
|
+
|
|
67
|
+
## Violations
|
|
68
|
+
|
|
69
|
+
The first time you are notified in writing that you have violated any of these terms, or done anything with the software not covered by your licenses, your licenses can nonetheless continue if you come into full compliance with these terms, and take practical steps to correct past violations, within 32 days of receiving notice. Otherwise, all your licenses end immediately.
|
|
70
|
+
|
|
71
|
+
## No Liability
|
|
72
|
+
|
|
73
|
+
***As far as the law allows, the software comes as is, without any warranty or condition, and the licensor will not be liable to you for any damages arising out of these terms or the use or nature of the software, under any kind of legal claim.***
|
|
74
|
+
|
|
75
|
+
## Definitions
|
|
76
|
+
|
|
77
|
+
The **licensor** is the individual or entity offering these terms, and the **software** is the software the licensor makes available under these terms.
|
|
78
|
+
|
|
79
|
+
A **product** can be a good or service, or a combination of them.
|
|
80
|
+
|
|
81
|
+
**You** refers to the individual or entity agreeing to these terms.
|
|
82
|
+
|
|
83
|
+
**Your company** is any legal entity, sole proprietorship, or other kind of organization that you work for, plus all its affiliates.
|
|
84
|
+
|
|
85
|
+
**Affiliates** means the other organizations than an organization has control over, is under the control of, or is under common control with.
|
|
86
|
+
|
|
87
|
+
**Control** means ownership of substantially all the assets of an entity, or the power to direct its management and policies by vote, contract, or otherwise. Control can be direct or indirect.
|
|
88
|
+
|
|
89
|
+
**Your licenses** are all the licenses granted to you for the software under these terms.
|
|
90
|
+
|
|
91
|
+
**Use** means anything you do with the software requiring one of your licenses.
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
# Additional Permission — Aventara
|
|
2
|
+
|
|
3
|
+
Copyright 2026 Mohamed Ragheb
|
|
4
|
+
|
|
5
|
+
In addition to the permissions of the PolyForm Shield License 1.0.0 in `LICENSE`, the licensor grants the following additional permission:
|
|
6
|
+
|
|
7
|
+
The Noncompete section applies only to providing a product that competes with the software itself — the Aventara framework, its packages and its tooling. Providing a product that competes with any other product the licensor or its affiliates provide using the software is a permitted purpose.
|
|
8
|
+
|
|
9
|
+
This additional permission only adds to your permissions; it does not restrict or replace any term of `LICENSE`.
|
package/README.md
CHANGED
|
@@ -1,3 +1,145 @@
|
|
|
1
|
-
#
|
|
1
|
+
# `@aventara/mcp`
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The MCP server of an Aventara application. It turns the configuration's `agent` layer into
|
|
4
|
+
[Model Context Protocol](https://modelcontextprotocol.io) tools, so an AI agent (Claude Desktop, Claude Code, any MCP
|
|
5
|
+
client) can read and write the application's data under the same validation, exposure and pipelines as every other
|
|
6
|
+
caller.
|
|
7
|
+
|
|
8
|
+
The server lives inside your application. `@aventara/nest` mounts it at the path the configuration's `mcp` key names,
|
|
9
|
+
over the Streamable HTTP transport, stateless. You install this package beside `@aventara/nest`; you do not call it
|
|
10
|
+
yourself.
|
|
11
|
+
|
|
12
|
+
```bash
|
|
13
|
+
npm install @aventara/mcp@rc
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
It depends on `@aventara/core` and the official MCP TypeScript SDK (`@modelcontextprotocol/sdk`).
|
|
17
|
+
|
|
18
|
+
## Turning it on
|
|
19
|
+
|
|
20
|
+
```ts
|
|
21
|
+
// src/aventara.config.ts
|
|
22
|
+
export async function aventaraConfig(prisma: PrismaService) {
|
|
23
|
+
return {
|
|
24
|
+
api: "/api",
|
|
25
|
+
mcp: "/mcp",
|
|
26
|
+
adapter: await createPrismaAdapter({ client: prisma, discovery, provider: "postgresql", driver: "@prisma/adapter-pg" }),
|
|
27
|
+
// What the agent may reach: by default exactly what the client may.
|
|
28
|
+
agent: {
|
|
29
|
+
exposed: true,
|
|
30
|
+
exemptions: { resources: { AuditLog: true } },
|
|
31
|
+
},
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
When the configuration has `mcp`, `AventaraModule` mounts the endpoint and logs it:
|
|
37
|
+
`Aventara mounted the MCP endpoint at /mcp (…)`. With `mcp` set and this package missing, the application refuses to
|
|
38
|
+
start and names the package.
|
|
39
|
+
|
|
40
|
+
## The tools
|
|
41
|
+
|
|
42
|
+
One tool per operation family the agent layer exposes, and none for a family nothing exposes:
|
|
43
|
+
|
|
44
|
+
| Tool | Input | Hints |
|
|
45
|
+
|---|---|---|
|
|
46
|
+
| `find` | `{ resource, variant, args? }` | read-only |
|
|
47
|
+
| `create` | `{ resource, variant, args }` | not destructive |
|
|
48
|
+
| `update` | `{ resource, variant, args }` | destructive |
|
|
49
|
+
| `delete` | `{ resource, variant, args }` | destructive |
|
|
50
|
+
| `upsert` | `{ resource, variant, args }` | destructive |
|
|
51
|
+
| `transaction` | `{ steps: [{ resource, family, variant, args? }] }` | destructive |
|
|
52
|
+
|
|
53
|
+
`resource` and `variant` are enums read from the agent layer, so a resource the agent layer hides is not offered (and is
|
|
54
|
+
refused with `A2001` if an agent names it anyway). `args` is the operation's arguments as the protocol defines them
|
|
55
|
+
(`where`, `select`, `data`, …). `transaction` is offered when the agent layer's transactions are interactive. A step can
|
|
56
|
+
use a value an earlier step returned with `{ "$ref": { "operation": 0, "path": ["id"] } }`; the server adds the
|
|
57
|
+
fingerprints the protocol requires.
|
|
58
|
+
|
|
59
|
+
Every call runs as the `agent` origin, through the same decoding and validation as an HTTP call, with the agent
|
|
60
|
+
layer's pipelines. A success answers the protocol's envelope (`{ data, code, cause }`) as structured content and as
|
|
61
|
+
text. A failure answers an MCP tool error (`isError: true`) carrying the envelope, its cause and its issues (`path`,
|
|
62
|
+
`code`, `check`, `params`, `message`), so the agent can fix its arguments and call again.
|
|
63
|
+
|
|
64
|
+
## The contract resource
|
|
65
|
+
|
|
66
|
+
The server exposes the Agent Contract as the MCP resource `aventara://contract`: every resource, its fields and their
|
|
67
|
+
types, what can be filtered, selected, created and updated, and the request limits. The tool descriptions and the
|
|
68
|
+
server's instructions tell the agent to read it first.
|
|
69
|
+
|
|
70
|
+
## Write safety
|
|
71
|
+
|
|
72
|
+
What an agent can do is decided where everything else is: exposure (the `agent` layer, which can only narrow the layer
|
|
73
|
+
it extends) and guards. A guard can tell an agent's call by its origin:
|
|
74
|
+
|
|
75
|
+
```ts
|
|
76
|
+
const humansOnly: AvGuard = (ctx) => ctx.$origin !== "agent";
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
The tool hints (`readOnlyHint`, `destructiveHint`) are hints for the client; they enforce nothing.
|
|
80
|
+
|
|
81
|
+
## Authorization
|
|
82
|
+
|
|
83
|
+
With `mcp.authorization`, the endpoint is an OAuth 2.1 protected resource. It never issues tokens: your authorization
|
|
84
|
+
server does.
|
|
85
|
+
|
|
86
|
+
```ts
|
|
87
|
+
import { createRemoteJWKSet, jwtVerify } from "jose";
|
|
88
|
+
|
|
89
|
+
const jwks = createRemoteJWKSet(new URL("https://auth.example.com/.well-known/jwks.json"));
|
|
90
|
+
|
|
91
|
+
mcp: {
|
|
92
|
+
path: "/mcp",
|
|
93
|
+
authorization: {
|
|
94
|
+
servers: ["https://auth.example.com"],
|
|
95
|
+
verify: async (token) => {
|
|
96
|
+
try {
|
|
97
|
+
const { payload } = await jwtVerify(token, jwks, {
|
|
98
|
+
issuer: "https://auth.example.com",
|
|
99
|
+
audience: "https://api.example.com/mcp",
|
|
100
|
+
});
|
|
101
|
+
return payload;
|
|
102
|
+
} catch {
|
|
103
|
+
return null;
|
|
104
|
+
}
|
|
105
|
+
},
|
|
106
|
+
},
|
|
107
|
+
},
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
- `GET /.well-known/oauth-protected-resource/mcp` answers the protected-resource metadata (RFC 9728): the endpoint's
|
|
111
|
+
URL as `resource`, your `servers` as `authorization_servers`, and `bearer_methods_supported: ["header"]`.
|
|
112
|
+
- A request without `Authorization: Bearer <token>` is `401` with a `WWW-Authenticate` header naming that metadata,
|
|
113
|
+
which is how an MCP client discovers where to sign in.
|
|
114
|
+
- Each token goes to `verify`. `null` (or `undefined`, or a throw) is `401`. Anything else lets the request in, and
|
|
115
|
+
what `verify` returned is the request's `ctx.$state.mcp.claims`, beside what the host's `state` option seeds. Declare
|
|
116
|
+
its type with the rest of your state:
|
|
117
|
+
|
|
118
|
+
```ts
|
|
119
|
+
declare module "@aventara/core" {
|
|
120
|
+
interface AvState {
|
|
121
|
+
mcp?: { claims: JWTPayload };
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
The endpoint's URL comes from the request as your platform reports it, so behind a proxy set Express's `trust proxy`
|
|
127
|
+
or Fastify's `trustProxy` for `https` and the public host to appear in the metadata.
|
|
128
|
+
|
|
129
|
+
## Without authorization
|
|
130
|
+
|
|
131
|
+
An endpoint without `authorization` takes no token, so it answers callers on the same machine only: a loopback peer
|
|
132
|
+
address, no proxy forwarding header (`Forwarded`, `X-Forwarded-For`, `X-Real-IP`), and no `Origin` header but a
|
|
133
|
+
loopback one. Every other caller gets `403`. This is for local development and for an agent running beside the
|
|
134
|
+
application. To serve remote agents, configure `authorization`.
|
|
135
|
+
|
|
136
|
+
## The transport
|
|
137
|
+
|
|
138
|
+
Streamable HTTP, stateless: every `POST` is answered on its own with a JSON response, and no session is kept. `GET` and
|
|
139
|
+
`DELETE` answer `405`. A request body is limited to the agent layer's `maxRequestBytes`.
|
|
140
|
+
|
|
141
|
+
## License
|
|
142
|
+
|
|
143
|
+
PolyForm Shield 1.0.0 with an additional permission. It is free to use, including in commercial applications, but you
|
|
144
|
+
may not use it to build a product that competes with Aventara itself. See `LICENSE` and
|
|
145
|
+
`LICENSE-ADDITIONAL-PERMISSION.md`.
|
package/dist/av-mcp.d.ts
ADDED
package/dist/av-mcp.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { bind } from "./mcp.binder.js";
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import type { AvMcpEndpoint } from "@aventara/core";
|
|
2
|
+
import type { AvProtocolResponse } from "@aventara/core/protocol";
|
|
3
|
+
/** The authorization `mcp.authorization` configures. */
|
|
4
|
+
export type EndpointAuthorization = NonNullable<AvMcpEndpoint["authorization"]>;
|
|
5
|
+
/** What a request to the endpoint is let through with, or the answer that refuses it. */
|
|
6
|
+
export type EndpointAccess = {
|
|
7
|
+
readonly ok: true;
|
|
8
|
+
/** What `verify` resolved the token to; absent on an open endpoint. */
|
|
9
|
+
readonly caller?: {
|
|
10
|
+
readonly claims: unknown;
|
|
11
|
+
};
|
|
12
|
+
} | {
|
|
13
|
+
readonly ok: false;
|
|
14
|
+
readonly response: AvProtocolResponse;
|
|
15
|
+
};
|
|
16
|
+
/** The protected-resource metadata path for an endpoint at `endpointPath` (canonical, `""` at the root). */
|
|
17
|
+
export declare function metadataPathOf(endpointPath: string): string;
|
|
18
|
+
/** One JSON answer. */
|
|
19
|
+
export declare function jsonAnswer(status: number, body: unknown, headers?: Readonly<Record<string, string>>): AvProtocolResponse;
|
|
20
|
+
/**
|
|
21
|
+
* The protected-resource metadata document (RFC 9728 §2): the endpoint's URL as
|
|
22
|
+
* `resource`, the configured servers, and the one bearer method the endpoint
|
|
23
|
+
* reads, the `Authorization` header. Public, and readable from any origin.
|
|
24
|
+
*/
|
|
25
|
+
export declare function metadataAnswer(method: string, origin: string, endpointPath: string, authorization: EndpointAuthorization): AvProtocolResponse;
|
|
26
|
+
/**
|
|
27
|
+
* A protected endpoint's check: the request's bearer token, verified. A missing
|
|
28
|
+
* token, one `verify` rejects (`null`, `undefined`) and a `verify` that throws
|
|
29
|
+
* are each `401`; a good one passes with what `verify` resolved it to.
|
|
30
|
+
*/
|
|
31
|
+
export declare function authorizedAccess(authorizationHeader: string | undefined, origin: string, endpointPath: string, authorization: EndpointAuthorization): Promise<EndpointAccess>;
|
|
32
|
+
/** An open endpoint's check: the caller is on this machine. */
|
|
33
|
+
export declare function loopbackAccess(remoteAddress: string | undefined, header: (name: string) => string | undefined): EndpointAccess;
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
const METADATA_PREFIX = "/.well-known/oauth-protected-resource";
|
|
2
|
+
export function metadataPathOf(endpointPath) {
|
|
3
|
+
return `${METADATA_PREFIX}${endpointPath}`;
|
|
4
|
+
}
|
|
5
|
+
export function jsonAnswer(status, body, headers = {}) {
|
|
6
|
+
return {
|
|
7
|
+
status,
|
|
8
|
+
headers: { "Content-Type": "application/json", ...headers },
|
|
9
|
+
body: JSON.stringify(body),
|
|
10
|
+
};
|
|
11
|
+
}
|
|
12
|
+
export function metadataAnswer(method, origin, endpointPath, authorization) {
|
|
13
|
+
if (method !== "GET") {
|
|
14
|
+
return jsonAnswer(405, { error: "method_not_allowed", error_description: "Use GET." }, { Allow: "GET" });
|
|
15
|
+
}
|
|
16
|
+
return jsonAnswer(200, {
|
|
17
|
+
resource: `${origin}${endpointPath}`,
|
|
18
|
+
authorization_servers: [...authorization.servers],
|
|
19
|
+
bearer_methods_supported: ["header"],
|
|
20
|
+
}, { "Access-Control-Allow-Origin": "*", "Cache-Control": "no-cache" });
|
|
21
|
+
}
|
|
22
|
+
function bearerTokenOf(header) {
|
|
23
|
+
const match = /^Bearer[ \t]+([^ \t].*?)[ \t]*$/i.exec(header ?? "");
|
|
24
|
+
return match?.[1];
|
|
25
|
+
}
|
|
26
|
+
function challenge(origin, endpointPath, description) {
|
|
27
|
+
const metadata = `${origin}${metadataPathOf(endpointPath)}`;
|
|
28
|
+
return jsonAnswer(401, { error: "invalid_token", error_description: description }, {
|
|
29
|
+
"WWW-Authenticate": `Bearer error="invalid_token", error_description="${description}", resource_metadata="${metadata}"`,
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
export async function authorizedAccess(authorizationHeader, origin, endpointPath, authorization) {
|
|
33
|
+
const token = bearerTokenOf(authorizationHeader);
|
|
34
|
+
if (token === undefined) {
|
|
35
|
+
return {
|
|
36
|
+
ok: false,
|
|
37
|
+
response: challenge(origin, endpointPath, "Missing Authorization header"),
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
let claims;
|
|
41
|
+
try {
|
|
42
|
+
claims = await authorization.verify(token);
|
|
43
|
+
}
|
|
44
|
+
catch {
|
|
45
|
+
claims = null;
|
|
46
|
+
}
|
|
47
|
+
if (claims === null || claims === undefined) {
|
|
48
|
+
return {
|
|
49
|
+
ok: false,
|
|
50
|
+
response: challenge(origin, endpointPath, "The access token is invalid"),
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
return { ok: true, caller: { claims } };
|
|
54
|
+
}
|
|
55
|
+
const FORWARDING_HEADERS = ["forwarded", "x-forwarded-for", "x-real-ip"];
|
|
56
|
+
function isLoopbackAddress(address) {
|
|
57
|
+
if (address === undefined) {
|
|
58
|
+
return false;
|
|
59
|
+
}
|
|
60
|
+
const v4 = address.startsWith("::ffff:") ? address.slice(7) : address;
|
|
61
|
+
return address === "::1" || /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(v4);
|
|
62
|
+
}
|
|
63
|
+
function isLoopbackOrigin(origin) {
|
|
64
|
+
try {
|
|
65
|
+
const { hostname } = new URL(origin);
|
|
66
|
+
return (hostname === "localhost" ||
|
|
67
|
+
hostname === "[::1]" ||
|
|
68
|
+
isLoopbackAddress(hostname));
|
|
69
|
+
}
|
|
70
|
+
catch {
|
|
71
|
+
return false;
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
const LOOPBACK_ONLY = "This MCP endpoint has no authorization, so it answers callers on this machine only. Configure mcp.authorization to serve remote agents.";
|
|
75
|
+
export function loopbackAccess(remoteAddress, header) {
|
|
76
|
+
const origin = header("origin");
|
|
77
|
+
const local = isLoopbackAddress(remoteAddress) &&
|
|
78
|
+
FORWARDING_HEADERS.every((name) => header(name) === undefined) &&
|
|
79
|
+
(origin === undefined || isLoopbackOrigin(origin));
|
|
80
|
+
return local
|
|
81
|
+
? { ok: true }
|
|
82
|
+
: {
|
|
83
|
+
ok: false,
|
|
84
|
+
response: jsonAnswer(403, {
|
|
85
|
+
error: "forbidden",
|
|
86
|
+
error_description: LOOPBACK_ONLY,
|
|
87
|
+
}),
|
|
88
|
+
};
|
|
89
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@aventara/mcp`: the MCP server for an Aventara application. A host (the
|
|
3
|
+
* Nest module) mounts it at `framework.mcp.path`; it mounts nothing itself.
|
|
4
|
+
*/
|
|
5
|
+
export * as AvMcp from "./av-mcp.js";
|
|
6
|
+
export type { AvMcpBinding, AvMcpRequest } from "./mcp.binder.js";
|
package/dist/index.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * as AvMcp from "./av-mcp.js";
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `JSON.stringify(value)`'s text for JSON data (what an MCP message parses to),
|
|
3
|
+
* written without recursing on its depth: object members in their own order,
|
|
4
|
+
* a member whose value has no JSON form left out, and such a value in a list
|
|
5
|
+
* written `null`, as `JSON.stringify` does.
|
|
6
|
+
*/
|
|
7
|
+
export declare function jsonTextOf(value: unknown): string;
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
export function jsonTextOf(value) {
|
|
2
|
+
const output = [];
|
|
3
|
+
const stack = [
|
|
4
|
+
{ value },
|
|
5
|
+
];
|
|
6
|
+
while (stack.length > 0) {
|
|
7
|
+
const task = stack.pop();
|
|
8
|
+
if ("text" in task) {
|
|
9
|
+
output.push(task.text);
|
|
10
|
+
continue;
|
|
11
|
+
}
|
|
12
|
+
const current = task.value;
|
|
13
|
+
if (typeof current !== "object" || current === null) {
|
|
14
|
+
output.push(JSON.stringify(current) ?? "null");
|
|
15
|
+
continue;
|
|
16
|
+
}
|
|
17
|
+
if (Array.isArray(current)) {
|
|
18
|
+
output.push("[");
|
|
19
|
+
stack.push({ text: "]" });
|
|
20
|
+
for (let index = current.length - 1; index >= 0; index -= 1) {
|
|
21
|
+
stack.push({ value: current[index] });
|
|
22
|
+
if (index > 0) {
|
|
23
|
+
stack.push({ text: "," });
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
continue;
|
|
27
|
+
}
|
|
28
|
+
const record = current;
|
|
29
|
+
const keys = Object.keys(record).filter((key) => hasJsonForm(record[key]));
|
|
30
|
+
output.push("{");
|
|
31
|
+
stack.push({ text: "}" });
|
|
32
|
+
for (let index = keys.length - 1; index >= 0; index -= 1) {
|
|
33
|
+
const key = keys[index];
|
|
34
|
+
stack.push({ value: record[key] });
|
|
35
|
+
stack.push({ text: `${index > 0 ? "," : ""}${JSON.stringify(key)}:` });
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
return output.join("");
|
|
39
|
+
}
|
|
40
|
+
function hasJsonForm(value) {
|
|
41
|
+
return (value !== undefined &&
|
|
42
|
+
typeof value !== "function" &&
|
|
43
|
+
typeof value !== "symbol");
|
|
44
|
+
}
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import type { AvFramework, AvState } from "@aventara/core";
|
|
2
|
+
import { type AvProtocolResponse } from "@aventara/core/protocol";
|
|
3
|
+
/**
|
|
4
|
+
* One HTTP request to the MCP endpoint or its metadata, as a host hands it to
|
|
5
|
+
* the binding.
|
|
6
|
+
*/
|
|
7
|
+
export type AvMcpRequest = {
|
|
8
|
+
/** The HTTP method as received. */
|
|
9
|
+
readonly method: string;
|
|
10
|
+
/**
|
|
11
|
+
* The request's absolute URL as the host sees it (scheme, host, path,
|
|
12
|
+
* query), its proxy settings applied. The OAuth metadata names the endpoint
|
|
13
|
+
* by its origin.
|
|
14
|
+
*/
|
|
15
|
+
readonly url: string;
|
|
16
|
+
/** The request headers as received; a repeated header as its list of values. */
|
|
17
|
+
readonly headers: Readonly<Record<string, string | readonly string[] | undefined>>;
|
|
18
|
+
/** The body as received: at most `maxRequestBytes + 1` bytes are needed. */
|
|
19
|
+
readonly body: string | Uint8Array;
|
|
20
|
+
/**
|
|
21
|
+
* The socket peer's address. An endpoint without `authorization` answers
|
|
22
|
+
* loopback callers only.
|
|
23
|
+
*/
|
|
24
|
+
readonly remoteAddress?: string | undefined;
|
|
25
|
+
};
|
|
26
|
+
/** The routes a host mounts: the endpoint, then its OAuth metadata when it has `authorization`. */
|
|
27
|
+
type McpRoute = {
|
|
28
|
+
/** `endpoint`: answered by `handleEndpoint`; `metadata`: by `encodeMetadata`. */
|
|
29
|
+
readonly kind: "endpoint" | "metadata";
|
|
30
|
+
/** The absolute path. */
|
|
31
|
+
readonly path: string;
|
|
32
|
+
/** The methods to mount on it; the binding answers each, a refusal included. */
|
|
33
|
+
readonly methods: readonly ("GET" | "POST" | "DELETE")[];
|
|
34
|
+
};
|
|
35
|
+
/** The MCP server bound to one Framework, as `AvMcp.bind` returns it. */
|
|
36
|
+
export type AvMcpBinding = {
|
|
37
|
+
/**
|
|
38
|
+
* The routes to mount: the endpoint at `framework.mcp.path` (`/` at the
|
|
39
|
+
* root) for `POST`, `GET` and `DELETE` (the Streamable HTTP methods; this
|
|
40
|
+
* stateless endpoint answers the last two `405`), and, when the
|
|
41
|
+
* configuration has `mcp.authorization`, the protected-resource metadata at
|
|
42
|
+
* `/.well-known/oauth-protected-resource` followed by the endpoint's path,
|
|
43
|
+
* for `GET`.
|
|
44
|
+
*/
|
|
45
|
+
readonly surface: () => readonly McpRoute[];
|
|
46
|
+
/** The largest request body the endpoint reads: the Agent Contract's `maxRequestBytes`. */
|
|
47
|
+
readonly maxRequestBytes: number;
|
|
48
|
+
/**
|
|
49
|
+
* Answers one request to the endpoint: the caller checked (a bearer token
|
|
50
|
+
* through `verify`, or, with no `authorization`, a caller on this machine),
|
|
51
|
+
* then the MCP message answered as JSON, statelessly. A tool call runs as an
|
|
52
|
+
* agent-origin protocol request. Never rejects: a failure of its own (the MCP
|
|
53
|
+
* SDK's) is answered `500` with no detail and reported to the Framework's
|
|
54
|
+
* diagnostics sink as an `AvMcpDiagnostic`.
|
|
55
|
+
*/
|
|
56
|
+
readonly handleEndpoint: (request: AvMcpRequest, options?: {
|
|
57
|
+
/**
|
|
58
|
+
* Seeds each tool call's `ctx.$state`, as for a protocol request. With
|
|
59
|
+
* `authorization`, the state also carries `mcp: { claims }`: what
|
|
60
|
+
* `verify` resolved the token to.
|
|
61
|
+
*/
|
|
62
|
+
readonly state?: () => AvState | Promise<AvState>;
|
|
63
|
+
}) => Promise<AvProtocolResponse>;
|
|
64
|
+
/** Answers the protected-resource metadata route (RFC 9728). */
|
|
65
|
+
readonly encodeMetadata: (request: AvMcpRequest) => AvProtocolResponse;
|
|
66
|
+
};
|
|
67
|
+
/**
|
|
68
|
+
* `AvMcp.bind(framework)`: the MCP server for a Framework whose configuration
|
|
69
|
+
* has `mcp`, bound once at startup. Its tools and its contract resource are read
|
|
70
|
+
* from the Agent Contract now.
|
|
71
|
+
*/
|
|
72
|
+
export declare function bind(framework: AvFramework): AvMcpBinding;
|
|
73
|
+
export {};
|