@open-wa/mcp 5.0.0-alpha.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/.turbo/turbo-build.log +33 -0
- package/.turbo/turbo-test.log +16 -0
- package/CHANGELOG.md +25 -0
- package/LICENSE.md +67 -0
- package/README.md +19 -0
- package/dist/index.cjs +309 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +244 -0
- package/dist/index.d.mts +244 -0
- package/dist/index.mjs +299 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +48 -0
- package/src/adapter/hono-mcp.ts +207 -0
- package/src/execution/args.ts +59 -0
- package/src/execution/errors.ts +56 -0
- package/src/execution/invoke.ts +32 -0
- package/src/execution/kernel.ts +104 -0
- package/src/index.ts +7 -0
- package/src/manifest.ts +91 -0
- package/src/tool-naming.ts +11 -0
- package/test/adapter.test.ts +181 -0
- package/test/kernel.test.ts +151 -0
- package/test/manifest.test.ts +61 -0
- package/tsdown.config.ts +12 -0
- package/vitest.config.ts +10 -0
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
|
|
2
|
+
> @open-wa/mcp@5.0.0-alpha.0 build /Users/Mohammed/projects/tools/wa/packages/mcp
|
|
3
|
+
> tsdown
|
|
4
|
+
|
|
5
|
+
[34mβΉ[39m [34mtsdown v0.21.7[39m powered by [38;2;255;126;23mrolldown v1.0.0-rc.12[39m
|
|
6
|
+
[34mβΉ[39m config file: [4m/Users/Mohammed/projects/tools/wa/packages/mcp/tsdown.config.ts[24m
|
|
7
|
+
[34mβΉ[39m entry: [34m./src/index.ts[39m
|
|
8
|
+
[34mβΉ[39m tsconfig: [34m../../tsconfig.json[39m
|
|
9
|
+
[34mβΉ[39m Build start
|
|
10
|
+
[34mβΉ[39m Cleaning 6 files
|
|
11
|
+
[34mβΉ[39m [33m[CJS][39m [2mdist/[22m[1mindex.cjs[22m [2m11.07 kB[22m [2mβ gzip: 3.52 kB[22m
|
|
12
|
+
[34mβΉ[39m [33m[CJS][39m [2mdist/[22mindex.cjs.map [2m22.30 kB[22m [2mβ gzip: 6.54 kB[22m
|
|
13
|
+
[34mβΉ[39m [33m[CJS][39m 2 files, total: 33.38 kB
|
|
14
|
+
[33m[PLUGIN_TIMINGS] Warning:[0m Your build spent significant time in plugin `tsdown:deps`. See https://rolldown.rs/options/checks#plugintimings for more details.
|
|
15
|
+
|
|
16
|
+
[34mβΉ[39m [33m[CJS][39m [2mdist/[22m[32m[1mindex.d.cts[22m[39m [2m7.29 kB[22m [2mβ gzip: 2.45 kB[22m
|
|
17
|
+
[34mβΉ[39m [33m[CJS][39m 1 files, total: 7.29 kB
|
|
18
|
+
[33m[PLUGIN_TIMINGS] Warning:[0m Your build spent significant time in plugins. Here is a breakdown:
|
|
19
|
+
- rolldown-plugin-dts:generate (58%)
|
|
20
|
+
- tsdown:deps (25%)
|
|
21
|
+
See https://rolldown.rs/options/checks#plugintimings for more details.
|
|
22
|
+
|
|
23
|
+
[32mβ[39m Build complete in [32m5142ms[39m
|
|
24
|
+
[34mβΉ[39m [34m[ESM][39m [2mdist/[22m[1mindex.mjs[22m [2m10.29 kB[22m [2mβ gzip: 3.39 kB[22m
|
|
25
|
+
[34mβΉ[39m [34m[ESM][39m [2mdist/[22mindex.mjs.map [2m22.07 kB[22m [2mβ gzip: 6.47 kB[22m
|
|
26
|
+
[34mβΉ[39m [34m[ESM][39m [2mdist/[22m[32m[1mindex.d.mts[22m[39m [2m 7.29 kB[22m [2mβ gzip: 2.45 kB[22m
|
|
27
|
+
[34mβΉ[39m [34m[ESM][39m 3 files, total: 39.66 kB
|
|
28
|
+
[33m[PLUGIN_TIMINGS] Warning:[0m Your build spent significant time in plugins. Here is a breakdown:
|
|
29
|
+
- rolldown-plugin-dts:generate (77%)
|
|
30
|
+
- tsdown:deps (15%)
|
|
31
|
+
See https://rolldown.rs/options/checks#plugintimings for more details.
|
|
32
|
+
|
|
33
|
+
[32mβ[39m Build complete in [32m5148ms[39m
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
|
|
2
|
+
> @open-wa/mcp@5.0.0-alpha.0 test /Users/Mohammed/projects/tools/wa/packages/mcp
|
|
3
|
+
> vitest run
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
[1m[46m RUN [49m[22m [36mv4.1.2 [39m[90m/Users/Mohammed/projects/tools/wa/packages/mcp[39m
|
|
7
|
+
|
|
8
|
+
[32mβ[39m test/manifest.test.ts [2m([22m[2m6 tests[22m[2m)[22m[33m 491[2mms[22m[39m
|
|
9
|
+
[32mβ[39m test/kernel.test.ts [2m([22m[2m6 tests[22m[2m)[22m[32m 190[2mms[22m[39m
|
|
10
|
+
[32mβ[39m test/adapter.test.ts [2m([22m[2m7 tests[22m[2m)[22m[33m 407[2mms[22m[39m
|
|
11
|
+
|
|
12
|
+
[2m Test Files [22m [1m[32m3 passed[39m[22m[90m (3)[39m
|
|
13
|
+
[2m Tests [22m [1m[32m19 passed[39m[22m[90m (19)[39m
|
|
14
|
+
[2m Start at [22m 15:25:58
|
|
15
|
+
[2m Duration [22m 3.04s[2m (transform 1.05s, setup 0ms, import 3.92s, tests 1.09s, environment 0ms)[22m
|
|
16
|
+
|
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
# @open-wa/mcp
|
|
2
|
+
|
|
3
|
+
## 5.0.0-alpha.2
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- Dry run minor bump
|
|
8
|
+
|
|
9
|
+
### Patch Changes
|
|
10
|
+
|
|
11
|
+
- Updated dependencies []:
|
|
12
|
+
- @open-wa/config@6.0.0-alpha.2
|
|
13
|
+
- @open-wa/schema@6.0.0-alpha.2
|
|
14
|
+
- @open-wa/utils@6.0.0-alpha.2
|
|
15
|
+
|
|
16
|
+
## 5.0.1-alpha.2
|
|
17
|
+
|
|
18
|
+
### Patch Changes
|
|
19
|
+
|
|
20
|
+
- Dry run patch bump
|
|
21
|
+
|
|
22
|
+
- Updated dependencies []:
|
|
23
|
+
- @open-wa/config@5.0.1-alpha.2
|
|
24
|
+
- @open-wa/schema@5.0.1-alpha.2
|
|
25
|
+
- @open-wa/utils@5.0.1-alpha.2
|
package/LICENSE.md
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
### Copyright (c) 2020 Mohammed Shah
|
|
2
|
+
|
|
3
|
+
# Hippocratic + Do Not Harm (H-DNH) Version 1.1
|
|
4
|
+
|
|
5
|
+
## Preamble
|
|
6
|
+
|
|
7
|
+
Most software today is developed with little to no thought of how it will be used, or the consequences for our society and planet.
|
|
8
|
+
|
|
9
|
+
As software developers, we engineer the infrastructure of the 21st century. We recognise that our infrastructure has great power to shape the world and the lives of those we share it with, and we choose to consciously take responsibility for the social and environmental impacts of what we build.
|
|
10
|
+
|
|
11
|
+
We envisage a world free from injustice, inequality, and the reckless destruction of lives and our planet. We reject slavery in all its forms, whether by force, indebtedness, or by algorithms that hack human vulnerabilities. We seek a world where humankind is at peace with our neighbours, nature, and ourselves. We want our work to enrich the physical, mental and spiritual wellbeing of all society.
|
|
12
|
+
|
|
13
|
+
We build software to further this vision of a just world, or at the very least, to not put that vision further from reach.
|
|
14
|
+
|
|
15
|
+
## Terms
|
|
16
|
+
|
|
17
|
+
Licensor hereby grants permission by thisΒ license ("License"), free of charge, to any personΒ or entity (the "Licensee")Β obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
|
18
|
+
|
|
19
|
+
1. All redistribution of source code or binary form, including any modifications must be under these terms. You must inform recipients that the code is governed by these conditions, and how they can obtain a copy of this license. You may not attempt to alter the conditions of who may/may not use this software.
|
|
20
|
+
|
|
21
|
+
2. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
|
|
22
|
+
|
|
23
|
+
3. This software must not be used by any organisation, website, product or service that:
|
|
24
|
+
|
|
25
|
+
a) lobbies for, promotes, or derives a majority of income from actions that support or contribute to:
|
|
26
|
+
* sex trafficking
|
|
27
|
+
* human trafficking
|
|
28
|
+
* slavery
|
|
29
|
+
* indentured servitude
|
|
30
|
+
* gambling
|
|
31
|
+
* tobacco
|
|
32
|
+
* adversely addictive behaviours
|
|
33
|
+
* nuclear energy
|
|
34
|
+
* warfare
|
|
35
|
+
* weapons manufacturing
|
|
36
|
+
* war crimes
|
|
37
|
+
* settler colonialism
|
|
38
|
+
* apartheid
|
|
39
|
+
* vaccine misinformation
|
|
40
|
+
* climate misinformation
|
|
41
|
+
* child endangerment
|
|
42
|
+
* violence (except when required to protect public safety)
|
|
43
|
+
* burning of forests
|
|
44
|
+
* deforestation
|
|
45
|
+
* hate speech or discrimination based on age, gender, gender identity, race, sexuality, religion, nationality
|
|
46
|
+
|
|
47
|
+
b) lobbies against, or derives a majority of income from actions that discourage or frustrate:
|
|
48
|
+
* peace
|
|
49
|
+
* access to the rights set out in the Universal Declaration of Human Rights and the Convention on the Rights of the Child
|
|
50
|
+
* peaceful assembly and association (including worker associations)
|
|
51
|
+
* a safe environment or action to curtail the use of fossil fuels or prevent climate change
|
|
52
|
+
* democratic processes
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
4. Compliance with Human Rights Laws and Human Rights Principles:
|
|
56
|
+
|
|
57
|
+
a. **Human Rights Laws**. TheΒ Software shall not be used byΒ any person or entityΒ for any systems,Β activities, or other usesΒ thatΒ violate anyΒ applicable laws, regulations, or rules that protect human, civil, labor, privacy, political, environmental, security, economic, due process, or similar rights (the "Human Rights Laws"). Where the Human Rights Laws of more than one jurisdiction are applicable to the use of the Software, the Human Rights Laws that are most protective of the individuals or groups harmed shall apply.
|
|
58
|
+
|
|
59
|
+
b. **Human Rights Principles**. Licensee is advised to consult the articles of the United Nations Universal Declaration of Human Rights (https://www.un.org/en/universal-declaration-human-rights/) and the United Nations Global Compact (https://www.unglobalcompact.org/ what-is-gc/mission/principles) that define recognized principles of international human rights (the "Human Rights Principles"). It is Licensor's express intent that all use of the Software be consistent with Human Rights Principles. If Licensor receives notification or otherwise learns of an alleged violation of any Human Rights Principles relating to Licensee's use of the Software, Licensor may in its discretion and without obligation (i) (a) notify Licensee of such allegation and (b) allow Licensee 90 days from notification under (i)(a) to investigate and respond to Licensor regarding the allegation and (ii) (a) after the earlier of 90 days from notification under (i)(a), or Licensee's response under (i)(b), notify Licensee of License termination and (b) allow Licensee an additional 90 days from notification under (ii)(a) to cease use of the Software.
|
|
60
|
+
|
|
61
|
+
c. **Indemnity**. Licensee shall hold harmless and indemnify Licensor against all losses, damages, liabilities, deficiencies, claims, actions, judgments, settlements, interest, awards, penalties, fines, costs, or expenses of whatever kind, including Licensor's reasonable attorneys' fees, arising out of or relating to Licensee's non-compliance with this License or use of the Software in violation of Human Rights Laws or Human Rights Principles.Β
|
|
62
|
+
|
|
63
|
+
5. Enforceability: If any portion or provision of this LicenseΒ isΒ determined to beΒ invalid, illegal, or unenforceableΒ by a court of competent jurisdiction, thenΒ such invalidity, illegality, or unenforceability shall not affect any other term or provision of thisΒ LicenseΒ or invalidate or render unenforceable such term or provision in any other jurisdiction. Upon a determination that any term or provision is invalid, illegal, or unenforceable, to the extent permitted by applicable law, the court may modify this License to affect the original intent of the parties as closely as possible. The section headings are for convenience only and are not intended to affect the construction or interpretation of this License. Any rule of construction to the effect that ambiguities are to be resolved against the drafting party shall not apply in interpreting this License. The language in this License shall be interpreted as to its fair meaning and not strictly for or against any party.
|
|
64
|
+
|
|
65
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
|
66
|
+
|
|
67
|
+
This license is an extension of the Hippocratic License - an Ethical Source license (https://ethicalsource.dev) and the Do Not Harm License - (https://github.com/raisely/NoHarm)
|
package/README.md
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
# @open-wa/mcp
|
|
2
|
+
|
|
3
|
+
MCP server integration for open-wa
|
|
4
|
+
|
|
5
|
+
Part of the [@open-wa v5 monorepo](https://github.com/open-wa/wa-automate-nodejs).
|
|
6
|
+
|
|
7
|
+
## Install
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
pnpm add @open-wa/mcp
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
## Documentation
|
|
14
|
+
|
|
15
|
+
See the [docs site](https://docs.openwa.dev).
|
|
16
|
+
|
|
17
|
+
## License
|
|
18
|
+
|
|
19
|
+
[H-DNH V1.0](https://github.com/open-wa/wa-automate-nodejs/blob/main/LICENSE.md) β Hippocratic + Do Not Harm
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,309 @@
|
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
+
let _open_wa_schema_http_manifest = require("@open-wa/schema/http-manifest");
|
|
3
|
+
let _open_wa_schema = require("@open-wa/schema");
|
|
4
|
+
let _modelcontextprotocol_sdk_server_index_js = require("@modelcontextprotocol/sdk/server/index.js");
|
|
5
|
+
let _modelcontextprotocol_sdk_server_webStandardStreamableHttp_js = require("@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js");
|
|
6
|
+
let _modelcontextprotocol_sdk_types_js = require("@modelcontextprotocol/sdk/types.js");
|
|
7
|
+
let zod_to_json_schema = require("zod-to-json-schema");
|
|
8
|
+
//#region src/tool-naming.ts
|
|
9
|
+
/**
|
|
10
|
+
* Logic for stable, namespaced MCP tool names.
|
|
11
|
+
*/
|
|
12
|
+
/**
|
|
13
|
+
* Returns the canonical namespaced tool name for MCP.
|
|
14
|
+
* @example getCanonicalToolName('messages', 'sendText') -> 'messages.sendText'
|
|
15
|
+
*/
|
|
16
|
+
function getCanonicalToolName(namespace, methodName) {
|
|
17
|
+
return `${namespace}.${methodName}`;
|
|
18
|
+
}
|
|
19
|
+
//#endregion
|
|
20
|
+
//#region src/manifest.ts
|
|
21
|
+
/**
|
|
22
|
+
* Projects the schema registry into a list of canonical MCP tool definitions.
|
|
23
|
+
*/
|
|
24
|
+
function getMcpToolDefinitions(basePath = "/api") {
|
|
25
|
+
return (0, _open_wa_schema_http_manifest.getHttpMethodDefinitions)(basePath).map((def) => {
|
|
26
|
+
return {
|
|
27
|
+
toolName: getCanonicalToolName(def.namespace, def.namespacedName),
|
|
28
|
+
functionName: def.functionName,
|
|
29
|
+
namespacedName: def.namespacedName,
|
|
30
|
+
namespace: def.namespace,
|
|
31
|
+
description: def.description,
|
|
32
|
+
inputSchema: def.inputSchema,
|
|
33
|
+
outputSchema: def.outputSchema,
|
|
34
|
+
parameterOrder: def.parameterOrder,
|
|
35
|
+
aliases: def.aliases,
|
|
36
|
+
deprecatedAliases: def.deprecatedAliases,
|
|
37
|
+
keyAliasMap: def.keyAliasMap,
|
|
38
|
+
annotations: {
|
|
39
|
+
title: def.functionName,
|
|
40
|
+
readOnlyHint: def.functionName.startsWith("get") || def.functionName.startsWith("is")
|
|
41
|
+
}
|
|
42
|
+
};
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
//#endregion
|
|
46
|
+
//#region src/execution/args.ts
|
|
47
|
+
function mapArrayArgs(def, args) {
|
|
48
|
+
return def.parameterOrder.reduce((acc, key, index) => {
|
|
49
|
+
if (index < args.length) acc[key] = args[index];
|
|
50
|
+
return acc;
|
|
51
|
+
}, {});
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* Normalizes an input payload into a form suitable for schema validation.
|
|
55
|
+
* Handles:
|
|
56
|
+
* 1. Array-based positional arguments
|
|
57
|
+
* 2. Mixed key aliases (legacy vs canonical)
|
|
58
|
+
* 3. Wrapped 'args' or 'input' properties
|
|
59
|
+
*/
|
|
60
|
+
function normalizeMethodPayload(def, payload) {
|
|
61
|
+
if (Array.isArray(payload)) return (0, _open_wa_schema.normalizeParameterKeys)(mapArrayArgs(def, payload), def.keyAliasMap);
|
|
62
|
+
if (!payload || typeof payload !== "object") return {};
|
|
63
|
+
const record = payload;
|
|
64
|
+
if ("args" in record) {
|
|
65
|
+
const args = record.args;
|
|
66
|
+
if (Array.isArray(args)) return (0, _open_wa_schema.normalizeParameterKeys)(mapArrayArgs(def, args), def.keyAliasMap);
|
|
67
|
+
if (args && typeof args === "object") return (0, _open_wa_schema.normalizeParameterKeys)(args, def.keyAliasMap);
|
|
68
|
+
}
|
|
69
|
+
if (record.input && typeof record.input === "object" && !Array.isArray(record.input)) return (0, _open_wa_schema.normalizeParameterKeys)(record.input, def.keyAliasMap);
|
|
70
|
+
if (def.inputSchema instanceof _open_wa_schema.z.ZodObject) {
|
|
71
|
+
const knownKeys = new Set(Object.keys(def.inputSchema.shape));
|
|
72
|
+
const filtered = Object.fromEntries(Object.entries(record).filter(([key]) => knownKeys.has(key)));
|
|
73
|
+
if (Object.keys(filtered).length > 0) return (0, _open_wa_schema.normalizeParameterKeys)(filtered, def.keyAliasMap);
|
|
74
|
+
}
|
|
75
|
+
return (0, _open_wa_schema.normalizeParameterKeys)(record, def.keyAliasMap);
|
|
76
|
+
}
|
|
77
|
+
//#endregion
|
|
78
|
+
//#region src/execution/invoke.ts
|
|
79
|
+
/**
|
|
80
|
+
* Invokes a client method by resolving its implementation from the client instance
|
|
81
|
+
* and mapping the payload to positional arguments if necessary.
|
|
82
|
+
*/
|
|
83
|
+
async function invokeClientMethod(client, def, payload) {
|
|
84
|
+
if (!client) throw new Error("Client not initialized");
|
|
85
|
+
const method = client[def.functionName] ?? (def.wapiOverride ? client[def.wapiOverride] : void 0);
|
|
86
|
+
if (typeof method !== "function") throw new Error(`Method ${def.functionName} not implemented on Client`);
|
|
87
|
+
if (!payload || typeof payload !== "object" || Array.isArray(payload)) return await method.call(client);
|
|
88
|
+
const resolvedArgs = def.parameterOrder.map((key) => payload[key]);
|
|
89
|
+
return await method.call(client, ...resolvedArgs);
|
|
90
|
+
}
|
|
91
|
+
//#endregion
|
|
92
|
+
//#region src/execution/kernel.ts
|
|
93
|
+
/**
|
|
94
|
+
* The shared execution kernel for Open-WA capabilities.
|
|
95
|
+
* Ensures strict parity between HTTP API and MCP transport by centralizing
|
|
96
|
+
* normalization, validation, and invocation logic.
|
|
97
|
+
*/
|
|
98
|
+
async function executeCapability(ctx) {
|
|
99
|
+
const { client, definition, payload, elasticEmitter, sessionId } = ctx;
|
|
100
|
+
const startTime = Date.now();
|
|
101
|
+
const methodName = definition.functionName;
|
|
102
|
+
try {
|
|
103
|
+
const normalizedPayload = normalizeMethodPayload(definition, payload);
|
|
104
|
+
const result = await invokeClientMethod(client, definition, await definition.inputSchema.parseAsync(normalizedPayload));
|
|
105
|
+
elasticEmitter?.log({
|
|
106
|
+
level: "info",
|
|
107
|
+
component: "api",
|
|
108
|
+
method: methodName,
|
|
109
|
+
sessionId,
|
|
110
|
+
duration: Date.now() - startTime,
|
|
111
|
+
statusCode: 200,
|
|
112
|
+
message: `Successfully executed ${methodName}`
|
|
113
|
+
});
|
|
114
|
+
return {
|
|
115
|
+
success: true,
|
|
116
|
+
data: result,
|
|
117
|
+
status: 200
|
|
118
|
+
};
|
|
119
|
+
} catch (error) {
|
|
120
|
+
const isValidationError = error?.name === "ZodError";
|
|
121
|
+
const status = isValidationError ? 400 : 500;
|
|
122
|
+
elasticEmitter?.log({
|
|
123
|
+
level: "error",
|
|
124
|
+
component: "api",
|
|
125
|
+
method: methodName,
|
|
126
|
+
sessionId,
|
|
127
|
+
duration: Date.now() - startTime,
|
|
128
|
+
statusCode: status,
|
|
129
|
+
message: error?.message || "Internal Server Error"
|
|
130
|
+
});
|
|
131
|
+
return {
|
|
132
|
+
success: false,
|
|
133
|
+
error: isValidationError ? "Validation Error" : error?.message || "Internal Server Error",
|
|
134
|
+
details: isValidationError ? error.issues : void 0,
|
|
135
|
+
status
|
|
136
|
+
};
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
//#endregion
|
|
140
|
+
//#region src/execution/errors.ts
|
|
141
|
+
/**
|
|
142
|
+
* MCP execution error types.
|
|
143
|
+
*
|
|
144
|
+
* Maintains the separation between protocol-level errors
|
|
145
|
+
* (JSON-RPC envelope issues) and tool-level errors
|
|
146
|
+
* (open-wa runtime invocation failures).
|
|
147
|
+
*/
|
|
148
|
+
/**
|
|
149
|
+
* A tool execution error from the open-wa runtime.
|
|
150
|
+
* This should be surfaced as `isError: true` in MCP tool results,
|
|
151
|
+
* NOT as a JSON-RPC protocol error.
|
|
152
|
+
*/
|
|
153
|
+
var ToolExecutionError = class extends Error {
|
|
154
|
+
constructor(message, statusCode = 500, details) {
|
|
155
|
+
super(message);
|
|
156
|
+
this.name = "ToolExecutionError";
|
|
157
|
+
this.statusCode = statusCode;
|
|
158
|
+
this.details = details;
|
|
159
|
+
}
|
|
160
|
+
};
|
|
161
|
+
/**
|
|
162
|
+
* A validation error from Zod schema parsing.
|
|
163
|
+
* This should be surfaced as `isError: true` in MCP tool results
|
|
164
|
+
* with the validation details attached.
|
|
165
|
+
*/
|
|
166
|
+
var ToolValidationError = class extends ToolExecutionError {
|
|
167
|
+
constructor(message, details) {
|
|
168
|
+
super(message, 400, details);
|
|
169
|
+
this.name = "ToolValidationError";
|
|
170
|
+
}
|
|
171
|
+
};
|
|
172
|
+
/**
|
|
173
|
+
* Thrown when the client/session is not ready for execution.
|
|
174
|
+
*/
|
|
175
|
+
var SessionNotReadyError = class extends ToolExecutionError {
|
|
176
|
+
constructor(message = "Session is not connected or ready for execution") {
|
|
177
|
+
super(message, 503);
|
|
178
|
+
this.name = "SessionNotReadyError";
|
|
179
|
+
}
|
|
180
|
+
};
|
|
181
|
+
/**
|
|
182
|
+
* Thrown when authentication is missing or invalid.
|
|
183
|
+
*/
|
|
184
|
+
var AuthenticationError = class extends ToolExecutionError {
|
|
185
|
+
constructor(message = "Authentication required. Provide a valid API key.") {
|
|
186
|
+
super(message, 401);
|
|
187
|
+
this.name = "AuthenticationError";
|
|
188
|
+
}
|
|
189
|
+
};
|
|
190
|
+
//#endregion
|
|
191
|
+
//#region src/adapter/hono-mcp.ts
|
|
192
|
+
/**
|
|
193
|
+
* Creates an MCP adapter using the Streamable HTTP transport (single-endpoint).
|
|
194
|
+
*
|
|
195
|
+
* open-wa product decision:
|
|
196
|
+
* hosted MCP is Easy API-only and unavailable through createClient()
|
|
197
|
+
*
|
|
198
|
+
* This adapter:
|
|
199
|
+
* - Uses WebStandardStreamableHTTPServerTransport for a single-endpoint /mcp shape
|
|
200
|
+
* - Enforces Easy API API-key auth on every request
|
|
201
|
+
* - Gates tool execution on session readiness (parity with HTTP transport)
|
|
202
|
+
* - Returns protocol errors for malformed protocol requests
|
|
203
|
+
* - Returns tool-level errors for open-wa execution failures
|
|
204
|
+
*/
|
|
205
|
+
function createHonoMcpAdapter(options) {
|
|
206
|
+
const { config, clientSource, elasticEmitter, basePath = "/api", isSessionConnected } = options;
|
|
207
|
+
const toolDefinitions = getMcpToolDefinitions(basePath);
|
|
208
|
+
const toolMap = new Map(toolDefinitions.map((d) => [d.toolName, d]));
|
|
209
|
+
const server = new _modelcontextprotocol_sdk_server_index_js.Server({
|
|
210
|
+
name: "open-wa",
|
|
211
|
+
version: "5.0.0"
|
|
212
|
+
}, { capabilities: { tools: {} } });
|
|
213
|
+
server.setRequestHandler(_modelcontextprotocol_sdk_types_js.ListToolsRequestSchema, async () => {
|
|
214
|
+
return { tools: toolDefinitions.map((def) => ({
|
|
215
|
+
name: def.toolName,
|
|
216
|
+
description: def.description,
|
|
217
|
+
inputSchema: (0, zod_to_json_schema.zodToJsonSchema)(def.inputSchema)
|
|
218
|
+
})) };
|
|
219
|
+
});
|
|
220
|
+
server.setRequestHandler(_modelcontextprotocol_sdk_types_js.CallToolRequestSchema, async (request) => {
|
|
221
|
+
const { name, arguments: args } = request.params;
|
|
222
|
+
const definition = toolMap.get(name);
|
|
223
|
+
if (!definition) return {
|
|
224
|
+
isError: true,
|
|
225
|
+
content: [{
|
|
226
|
+
type: "text",
|
|
227
|
+
text: `Unknown tool: ${name}. Use tools/list to discover available tools.`
|
|
228
|
+
}]
|
|
229
|
+
};
|
|
230
|
+
if (isSessionConnected && !isSessionConnected()) {
|
|
231
|
+
if (config.apiLifecycle !== "immediate") return {
|
|
232
|
+
isError: true,
|
|
233
|
+
content: [{
|
|
234
|
+
type: "text",
|
|
235
|
+
text: "Session is not connected or ready. Tool execution is blocked until the session is fully ready."
|
|
236
|
+
}]
|
|
237
|
+
};
|
|
238
|
+
}
|
|
239
|
+
const result = await executeCapability({
|
|
240
|
+
client: clientSource(),
|
|
241
|
+
definition,
|
|
242
|
+
payload: args || {},
|
|
243
|
+
elasticEmitter,
|
|
244
|
+
sessionId: config.sessionId
|
|
245
|
+
});
|
|
246
|
+
if (result.success) return { content: [{
|
|
247
|
+
type: "text",
|
|
248
|
+
text: JSON.stringify(result.data, null, 2)
|
|
249
|
+
}] };
|
|
250
|
+
return {
|
|
251
|
+
isError: true,
|
|
252
|
+
content: [{
|
|
253
|
+
type: "text",
|
|
254
|
+
text: result.error || "Internal Execution Error"
|
|
255
|
+
}]
|
|
256
|
+
};
|
|
257
|
+
});
|
|
258
|
+
const transport = new _modelcontextprotocol_sdk_server_webStandardStreamableHttp_js.WebStandardStreamableHTTPServerTransport({
|
|
259
|
+
sessionIdGenerator: () => crypto.randomUUID(),
|
|
260
|
+
onsessioninitialized: (sessionId) => {
|
|
261
|
+
elasticEmitter?.log({
|
|
262
|
+
level: "info",
|
|
263
|
+
component: "mcp",
|
|
264
|
+
message: `MCP session initialized: ${sessionId}`,
|
|
265
|
+
sessionId: config.sessionId
|
|
266
|
+
});
|
|
267
|
+
},
|
|
268
|
+
onsessionclosed: (sessionId) => {
|
|
269
|
+
elasticEmitter?.log({
|
|
270
|
+
level: "info",
|
|
271
|
+
component: "mcp",
|
|
272
|
+
message: `MCP session closed: ${sessionId}`,
|
|
273
|
+
sessionId: config.sessionId
|
|
274
|
+
});
|
|
275
|
+
}
|
|
276
|
+
});
|
|
277
|
+
server.connect(transport);
|
|
278
|
+
return {
|
|
279
|
+
mount: (app, path) => {
|
|
280
|
+
app.all(`${path}`, async (c) => {
|
|
281
|
+
if (config.apiKey) {
|
|
282
|
+
const resolvedKey = c.req.header("X-API-Key") || c.req.header("api_key") || c.req.header("key");
|
|
283
|
+
if (!resolvedKey || resolvedKey !== config.apiKey) return c.json({
|
|
284
|
+
error: "Unauthorized",
|
|
285
|
+
details: "Invalid or missing API key for MCP endpoint"
|
|
286
|
+
}, 401);
|
|
287
|
+
}
|
|
288
|
+
return await transport.handleRequest(c.req.raw);
|
|
289
|
+
});
|
|
290
|
+
},
|
|
291
|
+
close: async () => {
|
|
292
|
+
await transport.close();
|
|
293
|
+
await server.close();
|
|
294
|
+
}
|
|
295
|
+
};
|
|
296
|
+
}
|
|
297
|
+
//#endregion
|
|
298
|
+
exports.AuthenticationError = AuthenticationError;
|
|
299
|
+
exports.SessionNotReadyError = SessionNotReadyError;
|
|
300
|
+
exports.ToolExecutionError = ToolExecutionError;
|
|
301
|
+
exports.ToolValidationError = ToolValidationError;
|
|
302
|
+
exports.createHonoMcpAdapter = createHonoMcpAdapter;
|
|
303
|
+
exports.executeCapability = executeCapability;
|
|
304
|
+
exports.getCanonicalToolName = getCanonicalToolName;
|
|
305
|
+
exports.getMcpToolDefinitions = getMcpToolDefinitions;
|
|
306
|
+
exports.invokeClientMethod = invokeClientMethod;
|
|
307
|
+
exports.normalizeMethodPayload = normalizeMethodPayload;
|
|
308
|
+
|
|
309
|
+
//# sourceMappingURL=index.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["z","Server","ListToolsRequestSchema","CallToolRequestSchema","WebStandardStreamableHTTPServerTransport"],"sources":["../src/tool-naming.ts","../src/manifest.ts","../src/execution/args.ts","../src/execution/invoke.ts","../src/execution/kernel.ts","../src/execution/errors.ts","../src/adapter/hono-mcp.ts"],"sourcesContent":["/**\n * Logic for stable, namespaced MCP tool names.\n */\n\n/**\n * Returns the canonical namespaced tool name for MCP.\n * @example getCanonicalToolName('messages', 'sendText') -> 'messages.sendText'\n */\nexport function getCanonicalToolName(namespace: string, methodName: string): string {\n return `${namespace}.${methodName}`;\n}\n","import { getHttpMethodDefinitions, type HttpMethodDefinition } from '@open-wa/schema/http-manifest';\nimport { getCanonicalToolName } from './tool-naming';\n\n/**\n * MCP-specific projection of a method capability.\n */\nexport interface McpToolDefinition {\n /**\n * The canonical namespaced tool name for MCP.\n * @example 'messages.sendText'\n */\n toolName: string;\n /**\n * The raw function name in the client.\n * @example 'sendText'\n */\n functionName: string;\n /**\n * The namespaced name (method part only).\n * @example 'sendText'\n */\n namespacedName: string;\n /**\n * The namespace this method belongs to.\n * @example 'messages'\n */\n namespace: string;\n /**\n * Human-readable description of the tool.\n */\n description: string;\n /**\n * Zod input schema.\n */\n inputSchema: HttpMethodDefinition['inputSchema'];\n /**\n * Zod output schema.\n */\n outputSchema: HttpMethodDefinition['outputSchema'];\n /**\n * Preserved parameter order for positional resolution.\n */\n parameterOrder: string[];\n /**\n * Known aliases for this method.\n */\n aliases: string[];\n /**\n * Deprecated aliases for this method.\n */\n deprecatedAliases: string[];\n /**\n * Map of payload key aliases to canonical keys.\n */\n keyAliasMap: Record<string, string>;\n /**\n * Optional metadata hints for AI clients.\n */\n annotations?: {\n title?: string;\n readOnlyHint?: boolean;\n destructiveHint?: boolean;\n idempotentHint?: boolean;\n };\n}\n\n/**\n * Projects the schema registry into a list of canonical MCP tool definitions.\n */\nexport function getMcpToolDefinitions(basePath = '/api'): McpToolDefinition[] {\n return getHttpMethodDefinitions(basePath).map((def) => {\n return {\n toolName: getCanonicalToolName(def.namespace, def.namespacedName),\n functionName: def.functionName,\n namespacedName: def.namespacedName,\n namespace: def.namespace,\n description: def.description,\n inputSchema: def.inputSchema,\n outputSchema: def.outputSchema,\n parameterOrder: def.parameterOrder,\n aliases: def.aliases,\n deprecatedAliases: def.deprecatedAliases,\n keyAliasMap: def.keyAliasMap,\n annotations: {\n title: def.functionName,\n // Hints can be derived from method names or hardcoded metadata in future\n readOnlyHint: def.functionName.startsWith('get') || def.functionName.startsWith('is'),\n },\n };\n });\n}\n","import { normalizeParameterKeys, z, type HttpMethodDefinition } from '@open-wa/schema';\n\nfunction mapArrayArgs(def: HttpMethodDefinition, args: unknown[]): Record<string, unknown> {\n return def.parameterOrder.reduce<Record<string, unknown>>((acc, key, index) => {\n if (index < args.length) {\n acc[key] = args[index];\n }\n\n return acc;\n }, {});\n}\n\n/**\n * Normalizes an input payload into a form suitable for schema validation.\n * Handles:\n * 1. Array-based positional arguments\n * 2. Mixed key aliases (legacy vs canonical)\n * 3. Wrapped 'args' or 'input' properties\n */\nexport function normalizeMethodPayload(def: HttpMethodDefinition, payload: unknown): any {\n if (Array.isArray(payload)) {\n return normalizeParameterKeys(mapArrayArgs(def, payload), def.keyAliasMap);\n }\n\n if (!payload || typeof payload !== 'object') {\n return {};\n }\n\n const record = payload as Record<string, unknown>;\n\n if ('args' in record) {\n const args = record.args;\n\n if (Array.isArray(args)) {\n return normalizeParameterKeys(mapArrayArgs(def, args), def.keyAliasMap);\n }\n\n if (args && typeof args === 'object') {\n return normalizeParameterKeys(args as Record<string, any>, def.keyAliasMap);\n }\n }\n\n if (record.input && typeof record.input === 'object' && !Array.isArray(record.input)) {\n return normalizeParameterKeys(record.input as Record<string, any>, def.keyAliasMap);\n }\n\n if (def.inputSchema instanceof z.ZodObject) {\n const knownKeys = new Set(Object.keys(def.inputSchema.shape));\n const filtered = Object.fromEntries(\n Object.entries(record).filter(([key]) => knownKeys.has(key))\n );\n\n if (Object.keys(filtered).length > 0) {\n return normalizeParameterKeys(filtered, def.keyAliasMap);\n }\n }\n\n return normalizeParameterKeys(record, def.keyAliasMap);\n}\n","export interface ClientMethodDefinitionLike {\n functionName: string;\n parameterOrder: string[];\n wapiOverride?: string;\n}\n\n/**\n * Invokes a client method by resolving its implementation from the client instance\n * and mapping the payload to positional arguments if necessary.\n */\nexport async function invokeClientMethod(\n client: Record<string, (...args: any[]) => Promise<any> | any> | undefined,\n def: ClientMethodDefinitionLike,\n payload: unknown\n): Promise<any> {\n if (!client) {\n throw new Error('Client not initialized');\n }\n\n const method = client[def.functionName] ?? (def.wapiOverride ? client[def.wapiOverride] : undefined);\n\n if (typeof method !== 'function') {\n throw new Error(`Method ${def.functionName} not implemented on Client`);\n }\n\n if (!payload || typeof payload !== 'object' || Array.isArray(payload)) {\n return await method.call(client);\n }\n\n const resolvedArgs = def.parameterOrder.map((key) => (payload as Record<string, unknown>)[key]);\n return await method.call(client, ...resolvedArgs);\n}\n","import type { HttpMethodDefinition } from '@open-wa/schema';\nimport { normalizeMethodPayload } from './args';\nimport { invokeClientMethod } from './invoke';\n\n/**\n * Context required to execute an Open-WA capability via any transport.\n */\nexport interface ExecutionContext {\n /**\n * The active client instance or proxy.\n */\n client: Record<string, (...args: any[]) => Promise<any> | any> | undefined;\n /**\n * The metadata definition for the method being invoked.\n */\n definition: HttpMethodDefinition;\n /**\n * The raw input payload (merged query + body, or MCP arguments).\n */\n payload: Record<string, unknown>;\n /**\n * Optional diagnostic emitter for logging.\n */\n elasticEmitter?: {\n log: (data: any) => void;\n };\n /**\n * The unique session identifier.\n */\n sessionId: string;\n}\n\n/**\n * Standardized result of a capability execution.\n */\nexport interface ExecutionResult<T = any> {\n success: boolean;\n data?: T;\n error?: string;\n details?: any;\n status: number;\n}\n\n/**\n * The shared execution kernel for Open-WA capabilities.\n * Ensures strict parity between HTTP API and MCP transport by centralizing\n * normalization, validation, and invocation logic.\n */\nexport async function executeCapability(\n ctx: ExecutionContext\n): Promise<ExecutionResult> {\n const { client, definition, payload, elasticEmitter, sessionId } = ctx;\n const startTime = Date.now();\n const methodName = definition.functionName;\n\n try {\n // 1. Normalize aliases and legacy keys\n const normalizedPayload = normalizeMethodPayload(definition, payload);\n\n // 2. Validate against Zod schema (strict)\n const validated = await definition.inputSchema.parseAsync(normalizedPayload);\n\n // 3. Invoke the client method with positional argument resolution\n const result = await invokeClientMethod(client, definition, validated);\n\n // 4. Log successful execution to monitoring if available\n elasticEmitter?.log({\n level: 'info',\n component: 'api',\n method: methodName,\n sessionId,\n duration: Date.now() - startTime,\n statusCode: 200,\n message: `Successfully executed ${methodName}`,\n });\n\n return {\n success: true,\n data: result,\n status: 200,\n };\n } catch (error: any) {\n const isValidationError = error?.name === 'ZodError';\n const status = isValidationError ? 400 : 500;\n\n // Log failure to monitoring\n elasticEmitter?.log({\n level: 'error',\n component: 'api',\n method: methodName,\n sessionId,\n duration: Date.now() - startTime,\n statusCode: status,\n message: error?.message || 'Internal Server Error',\n });\n\n return {\n success: false,\n error: isValidationError ? 'Validation Error' : (error?.message || 'Internal Server Error'),\n details: isValidationError ? error.issues : undefined,\n status,\n };\n }\n}\n","/**\n * MCP execution error types.\n *\n * Maintains the separation between protocol-level errors\n * (JSON-RPC envelope issues) and tool-level errors\n * (open-wa runtime invocation failures).\n */\n\n/**\n * A tool execution error from the open-wa runtime.\n * This should be surfaced as `isError: true` in MCP tool results,\n * NOT as a JSON-RPC protocol error.\n */\nexport class ToolExecutionError extends Error {\n public readonly statusCode: number;\n public readonly details?: unknown;\n\n constructor(message: string, statusCode = 500, details?: unknown) {\n super(message);\n this.name = 'ToolExecutionError';\n this.statusCode = statusCode;\n this.details = details;\n }\n}\n\n/**\n * A validation error from Zod schema parsing.\n * This should be surfaced as `isError: true` in MCP tool results\n * with the validation details attached.\n */\nexport class ToolValidationError extends ToolExecutionError {\n constructor(message: string, details?: unknown) {\n super(message, 400, details);\n this.name = 'ToolValidationError';\n }\n}\n\n/**\n * Thrown when the client/session is not ready for execution.\n */\nexport class SessionNotReadyError extends ToolExecutionError {\n constructor(message = 'Session is not connected or ready for execution') {\n super(message, 503);\n this.name = 'SessionNotReadyError';\n }\n}\n\n/**\n * Thrown when authentication is missing or invalid.\n */\nexport class AuthenticationError extends ToolExecutionError {\n constructor(message = 'Authentication required. Provide a valid API key.') {\n super(message, 401);\n this.name = 'AuthenticationError';\n }\n}\n","import { Server } from '@modelcontextprotocol/sdk/server/index.js';\nimport { WebStandardStreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js';\nimport {\n CallToolRequestSchema,\n ListToolsRequestSchema,\n} from '@modelcontextprotocol/sdk/types.js';\nimport type { Hono, Context } from 'hono';\nimport { zodToJsonSchema } from 'zod-to-json-schema';\nimport type { Config } from '@open-wa/schema';\nimport { getMcpToolDefinitions } from '../manifest';\nimport { executeCapability } from '../execution/kernel';\n\nexport interface HonoMcpAdapterOptions {\n config: Config;\n /**\n * Getter for the active client instance.\n */\n clientSource: () => Record<string, any> | undefined;\n /**\n * Optional logging emitter.\n */\n elasticEmitter?: {\n log: (data: any) => void;\n };\n /**\n * Base path for tool documentation links.\n */\n basePath?: string;\n /**\n * Getter for session readiness state.\n * Used for lifecycle gating parity with HTTP transport.\n */\n isSessionConnected?: () => boolean;\n}\n\n/**\n * Creates an MCP adapter using the Streamable HTTP transport (single-endpoint).\n *\n * open-wa product decision:\n * hosted MCP is Easy API-only and unavailable through createClient()\n *\n * This adapter:\n * - Uses WebStandardStreamableHTTPServerTransport for a single-endpoint /mcp shape\n * - Enforces Easy API API-key auth on every request\n * - Gates tool execution on session readiness (parity with HTTP transport)\n * - Returns protocol errors for malformed protocol requests\n * - Returns tool-level errors for open-wa execution failures\n */\nexport function createHonoMcpAdapter(options: HonoMcpAdapterOptions) {\n const { config, clientSource, elasticEmitter, basePath = '/api', isSessionConnected } = options;\n const toolDefinitions = getMcpToolDefinitions(basePath);\n const toolMap = new Map(toolDefinitions.map((d) => [d.toolName, d]));\n\n const server = new Server(\n {\n name: 'open-wa',\n version: '5.0.0',\n },\n {\n capabilities: {\n tools: {},\n },\n }\n );\n\n // ββ tools/list ββββββββββββββββββββββββββββββββββββββββββββββββββββββ\n server.setRequestHandler(ListToolsRequestSchema, async () => {\n return {\n tools: toolDefinitions.map((def) => ({\n name: def.toolName,\n description: def.description,\n inputSchema: zodToJsonSchema(def.inputSchema) as any,\n })),\n };\n });\n\n // ββ tools/call ββββββββββββββββββββββββββββββββββββββββββββββββββββββ\n server.setRequestHandler(CallToolRequestSchema, async (request) => {\n const { name, arguments: args } = request.params;\n const definition = toolMap.get(name);\n\n if (!definition) {\n return {\n isError: true,\n content: [\n {\n type: 'text' as const,\n text: `Unknown tool: ${name}. Use tools/list to discover available tools.`,\n },\n ],\n };\n }\n\n // ββ Lifecycle/readiness gate (parity with HTTP transport) ββββββ\n if (isSessionConnected && !isSessionConnected()) {\n if (config.apiLifecycle !== 'immediate') {\n return {\n isError: true,\n content: [\n {\n type: 'text' as const,\n text: 'Session is not connected or ready. Tool execution is blocked until the session is fully ready.',\n },\n ],\n };\n }\n }\n\n const result = await executeCapability({\n client: clientSource(),\n definition: definition as any,\n payload: (args as Record<string, unknown>) || {},\n elasticEmitter,\n sessionId: config.sessionId,\n });\n\n if (result.success) {\n return {\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(result.data, null, 2),\n },\n ],\n };\n }\n\n return {\n isError: true,\n content: [\n {\n type: 'text' as const,\n text: result.error || 'Internal Execution Error',\n },\n ],\n };\n });\n\n // ββ Streamable HTTP transport βββββββββββββββββββββββββββββββββββββββ\n const transport = new WebStandardStreamableHTTPServerTransport({\n sessionIdGenerator: () => crypto.randomUUID(),\n onsessioninitialized: (sessionId: string) => {\n elasticEmitter?.log({\n level: 'info',\n component: 'mcp',\n message: `MCP session initialized: ${sessionId}`,\n sessionId: config.sessionId,\n });\n },\n onsessionclosed: (sessionId: string) => {\n elasticEmitter?.log({\n level: 'info',\n component: 'mcp',\n message: `MCP session closed: ${sessionId}`,\n sessionId: config.sessionId,\n });\n },\n });\n\n // Connect the server to the transport immediately\n server.connect(transport);\n\n return {\n /**\n * Mounts the MCP Streamable HTTP endpoint on the provided Hono app.\n *\n * This creates a single endpoint at `path` that handles:\n * - POST: JSON-RPC messages (initialize, tools/list, tools/call)\n * - GET: Server-initiated SSE stream\n * - DELETE: Session termination\n *\n * API-key auth is enforced on every request before delegation to MCP.\n */\n mount: (app: Hono, path: string) => {\n app.all(`${path}`, async (c: Context) => {\n // ββ API-key auth enforcement βββββββββββββββββββββββββββββββ\n // MCP inherits Easy API auth boundary. No key = no access.\n if (config.apiKey) {\n const headerKey =\n c.req.header('X-API-Key') ||\n c.req.header('api_key') ||\n c.req.header('key');\n const resolvedKey = headerKey;\n\n if (!resolvedKey || resolvedKey !== config.apiKey) {\n return c.json(\n { error: 'Unauthorized', details: 'Invalid or missing API key for MCP endpoint' },\n 401,\n );\n }\n }\n\n // ββ Delegate to Streamable HTTP transport ββββββββββββββββββ\n const response = await transport.handleRequest(c.req.raw);\n return response;\n });\n },\n\n /**\n * Cleanly shut down the MCP transport.\n */\n close: async () => {\n await transport.close();\n await server.close();\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;AAQA,SAAgB,qBAAqB,WAAmB,YAA4B;AAClF,QAAO,GAAG,UAAU,GAAG;;;;;;;AC4DzB,SAAgB,sBAAsB,WAAW,QAA6B;AAC5E,SAAA,GAAA,8BAAA,0BAAgC,SAAS,CAAC,KAAK,QAAQ;AACrD,SAAO;GACL,UAAU,qBAAqB,IAAI,WAAW,IAAI,eAAe;GACjE,cAAc,IAAI;GAClB,gBAAgB,IAAI;GACpB,WAAW,IAAI;GACf,aAAa,IAAI;GACjB,aAAa,IAAI;GACjB,cAAc,IAAI;GAClB,gBAAgB,IAAI;GACpB,SAAS,IAAI;GACb,mBAAmB,IAAI;GACvB,aAAa,IAAI;GACjB,aAAa;IACX,OAAO,IAAI;IAEX,cAAc,IAAI,aAAa,WAAW,MAAM,IAAI,IAAI,aAAa,WAAW,KAAK;IACtF;GACF;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