@cognexuslabs/artzain-mcp-gateway 0.0.0-stage → 0.1.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/CHANGELOG.md +7 -0
- package/LICENSE +202 -0
- package/README.md +45 -2
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +4 -0
- package/dist/config.d.ts +21 -0
- package/dist/config.js +120 -0
- package/dist/decide.d.ts +21 -0
- package/dist/decide.js +93 -0
- package/dist/server.d.ts +26 -0
- package/dist/server.js +219 -0
- package/dist/taxonomy.d.ts +18 -0
- package/dist/taxonomy.js +58 -0
- package/dist/taxonomy.json +62 -0
- package/dist/upstream.d.ts +53 -0
- package/dist/upstream.js +229 -0
- package/package.json +39 -4
package/CHANGELOG.md
ADDED
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this
|
|
152
|
+
License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright 2026 CogNEXUS Labs, LLC
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/README.md
CHANGED
|
@@ -1,3 +1,46 @@
|
|
|
1
|
-
#
|
|
1
|
+
# ArtzAIn MCP gateway
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
`@cognexuslabs/artzain-mcp-gateway` is an MCP server. It proxies the MCP servers listed in `gateway.json`. CogNEXUS Labs publishes it beside the TypeScript SDK and the OpenClaw, n8n, and Grok Bot packages.
|
|
4
|
+
|
|
5
|
+
A client sees one tool list. Each tool name is `<upstream>__<tool>`. `tools/call` asks the ArtzAIn Decision API before it forwards anything. The action and the target come from the W15 taxonomy shipped in this package (`src/taxonomy.json`). An entry in the upstream's `tools` map replaces the action for that tool name. The payload `tool` field is the action the rule matches.
|
|
6
|
+
|
|
7
|
+
Only an `allow` is forwarded. A `deny`, a `review`, an unrecognised outcome, a missing API key, and a Decision API outage all return `isError` and the upstream is not called. A review includes the decision id:
|
|
8
|
+
|
|
9
|
+
```text
|
|
10
|
+
QUEUED FOR REVIEW: this call needs human approval before it runs.
|
|
11
|
+
(decision <id>)
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
A deny includes the reason. An outage says the decision is unavailable and that the gateway is failing closed. There is no offline path.
|
|
15
|
+
|
|
16
|
+
Connectors which Grok Bot authenticates with its own OAuth may not be routable through the gateway. The first release targets self-hosted and API-key MCP servers.
|
|
17
|
+
|
|
18
|
+
## Configure
|
|
19
|
+
|
|
20
|
+
```json
|
|
21
|
+
{
|
|
22
|
+
"upstreams": [
|
|
23
|
+
{
|
|
24
|
+
"name": "notes",
|
|
25
|
+
"agent_id": "notes-bot",
|
|
26
|
+
"command": ["node", "server.js"],
|
|
27
|
+
"env": { "API_TOKEN": "set-this-outside-the-repo" },
|
|
28
|
+
"tools": { "save_doc": "write_file" }
|
|
29
|
+
}
|
|
30
|
+
]
|
|
31
|
+
}
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
Each upstream has a `name`, an `agent_id`, and exactly one of `command` (a string array) or `url` (http or https). `headers` and `env` are sent to that upstream and are not written to the gateway log. `tools` maps a raw tool name to an action.
|
|
35
|
+
|
|
36
|
+
The gateway reads `--config`, then `ARTZAIN_GATEWAY_CONFIG`, then `./gateway.json`. The Decision API key is `COGNEXUS_API_KEY`. `COGNEXUS_API_BASE_URL` defaults to `https://app.cognexuslabs.ai`. A child-process upstream does not inherit the gateway's environment, so its token belongs in that upstream's `env`.
|
|
37
|
+
|
|
38
|
+
```bash
|
|
39
|
+
node dist/cli.js --config gateway.json
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
Point an MCP client at that process over stdio. Logs stay on stderr, and stderr does not include upstream credentials or the API key.
|
|
43
|
+
|
|
44
|
+
## Develop
|
|
45
|
+
|
|
46
|
+
From this directory: `npm ci`, `npm test`, `npm run build`. The package version is `0.1.0`. It publishes from the public mirror on an `mcp-gateway-v<version>` tag.
|
package/dist/cli.d.ts
ADDED
package/dist/cli.js
ADDED
package/dist/config.d.ts
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* gateway.json lists the upstream MCP servers this process proxies.
|
|
3
|
+
* A header or env value is a credential. Nothing in this module prints it.
|
|
4
|
+
*/
|
|
5
|
+
export interface UpstreamConfig {
|
|
6
|
+
name: string;
|
|
7
|
+
agentId: string;
|
|
8
|
+
command?: string[];
|
|
9
|
+
url?: string;
|
|
10
|
+
headers?: Record<string, string>;
|
|
11
|
+
env?: Record<string, string>;
|
|
12
|
+
tools: Record<string, string>;
|
|
13
|
+
}
|
|
14
|
+
export interface GatewayConfig {
|
|
15
|
+
upstreams: UpstreamConfig[];
|
|
16
|
+
}
|
|
17
|
+
export declare class ConfigError extends Error {
|
|
18
|
+
constructor(message: string);
|
|
19
|
+
}
|
|
20
|
+
export declare function parseConfig(text: string): GatewayConfig;
|
|
21
|
+
export declare function loadConfig(path: string): GatewayConfig;
|
package/dist/config.js
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* gateway.json lists the upstream MCP servers this process proxies.
|
|
3
|
+
* A header or env value is a credential. Nothing in this module prints it.
|
|
4
|
+
*/
|
|
5
|
+
import { readFileSync } from "node:fs";
|
|
6
|
+
const NAME = /^[A-Za-z0-9][A-Za-z0-9_-]{0,40}$/;
|
|
7
|
+
export class ConfigError extends Error {
|
|
8
|
+
constructor(message) {
|
|
9
|
+
super(message);
|
|
10
|
+
this.name = "ConfigError";
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
function stringMap(value, label) {
|
|
14
|
+
if (value === undefined)
|
|
15
|
+
return {};
|
|
16
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
17
|
+
throw new ConfigError(`${label} must be an object of strings`);
|
|
18
|
+
}
|
|
19
|
+
const out = {};
|
|
20
|
+
for (const [key, item] of Object.entries(value)) {
|
|
21
|
+
if (typeof item !== "string" || item.length === 0) {
|
|
22
|
+
throw new ConfigError(`${label}.${key} must be a non-empty string`);
|
|
23
|
+
}
|
|
24
|
+
out[key] = item;
|
|
25
|
+
}
|
|
26
|
+
return out;
|
|
27
|
+
}
|
|
28
|
+
function oneUpstream(value, index) {
|
|
29
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
30
|
+
throw new ConfigError(`upstreams[${index}] must be an object`);
|
|
31
|
+
}
|
|
32
|
+
const row = value;
|
|
33
|
+
const name = row.name;
|
|
34
|
+
const agentId = row.agent_id;
|
|
35
|
+
if (typeof name !== "string" || !NAME.test(name)) {
|
|
36
|
+
throw new ConfigError(`upstreams[${index}].name must match ${NAME.source}`);
|
|
37
|
+
}
|
|
38
|
+
if (typeof agentId !== "string" || agentId.trim() === "") {
|
|
39
|
+
throw new ConfigError(`upstreams[${index}].agent_id must be a non-empty string`);
|
|
40
|
+
}
|
|
41
|
+
const command = row.command;
|
|
42
|
+
const url = row.url;
|
|
43
|
+
const hasCommand = command !== undefined;
|
|
44
|
+
const hasUrl = url !== undefined;
|
|
45
|
+
if (hasCommand === hasUrl) {
|
|
46
|
+
throw new ConfigError(`upstreams[${index}] needs exactly one of command or url`);
|
|
47
|
+
}
|
|
48
|
+
let parsedCommand;
|
|
49
|
+
let parsedUrl;
|
|
50
|
+
if (hasCommand) {
|
|
51
|
+
if (!Array.isArray(command) || command.length === 0 || command.some((part) => typeof part !== "string" || part === "")) {
|
|
52
|
+
throw new ConfigError(`upstreams[${index}].command must be a non-empty array of strings`);
|
|
53
|
+
}
|
|
54
|
+
parsedCommand = command;
|
|
55
|
+
}
|
|
56
|
+
else {
|
|
57
|
+
if (typeof url !== "string" || url.trim() === "") {
|
|
58
|
+
throw new ConfigError(`upstreams[${index}].url must be a non-empty string`);
|
|
59
|
+
}
|
|
60
|
+
let parsed;
|
|
61
|
+
try {
|
|
62
|
+
parsed = new URL(url);
|
|
63
|
+
}
|
|
64
|
+
catch {
|
|
65
|
+
throw new ConfigError(`upstreams[${index}].url is not a URL`);
|
|
66
|
+
}
|
|
67
|
+
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
|
|
68
|
+
throw new ConfigError(`upstreams[${index}].url must be http or https`);
|
|
69
|
+
}
|
|
70
|
+
parsedUrl = url;
|
|
71
|
+
}
|
|
72
|
+
return {
|
|
73
|
+
name,
|
|
74
|
+
agentId: agentId.trim(),
|
|
75
|
+
command: parsedCommand,
|
|
76
|
+
url: parsedUrl,
|
|
77
|
+
headers: stringMap(row.headers, `upstreams[${index}].headers`),
|
|
78
|
+
env: stringMap(row.env, `upstreams[${index}].env`),
|
|
79
|
+
tools: stringMap(row.tools, `upstreams[${index}].tools`),
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
export function parseConfig(text) {
|
|
83
|
+
let parsed;
|
|
84
|
+
try {
|
|
85
|
+
parsed = JSON.parse(text);
|
|
86
|
+
}
|
|
87
|
+
catch {
|
|
88
|
+
throw new ConfigError("gateway.json is not JSON");
|
|
89
|
+
}
|
|
90
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
|
|
91
|
+
throw new ConfigError("gateway.json must be an object");
|
|
92
|
+
}
|
|
93
|
+
const upstreams = parsed.upstreams;
|
|
94
|
+
if (!Array.isArray(upstreams) || upstreams.length === 0) {
|
|
95
|
+
throw new ConfigError("upstreams must be a non-empty array");
|
|
96
|
+
}
|
|
97
|
+
const rows = upstreams.map((row, index) => oneUpstream(row, index));
|
|
98
|
+
const names = rows.map((row) => row.name);
|
|
99
|
+
for (let i = 0; i < names.length; i += 1) {
|
|
100
|
+
for (let j = i + 1; j < names.length; j += 1) {
|
|
101
|
+
const left = names[i] ?? "";
|
|
102
|
+
const right = names[j] ?? "";
|
|
103
|
+
if (left === right || left.startsWith(`${right}_`) || right.startsWith(`${left}_`)) {
|
|
104
|
+
throw new ConfigError(`upstream names ${left} and ${right} overlap as tool prefixes`);
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
return { upstreams: rows };
|
|
109
|
+
}
|
|
110
|
+
export function loadConfig(path) {
|
|
111
|
+
let text;
|
|
112
|
+
try {
|
|
113
|
+
text = readFileSync(path, "utf8");
|
|
114
|
+
}
|
|
115
|
+
catch (err) {
|
|
116
|
+
const code = err.code ?? "unreadable";
|
|
117
|
+
throw new ConfigError(`cannot read the gateway config (${code})`);
|
|
118
|
+
}
|
|
119
|
+
return parseConfig(text);
|
|
120
|
+
}
|
package/dist/decide.d.ts
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* One Decision API call. A missing key, a transport failure, a redirect, or
|
|
3
|
+
* any outcome other than allow is a block. This client has no offline path:
|
|
4
|
+
* it never returns a synthetic allow.
|
|
5
|
+
*/
|
|
6
|
+
export interface DecisionRequest {
|
|
7
|
+
agentId: string;
|
|
8
|
+
action: string;
|
|
9
|
+
target: string;
|
|
10
|
+
payload: string;
|
|
11
|
+
requestId?: string;
|
|
12
|
+
}
|
|
13
|
+
export interface Decision {
|
|
14
|
+
outcome: string;
|
|
15
|
+
decisionId: string;
|
|
16
|
+
reasons: string[];
|
|
17
|
+
}
|
|
18
|
+
export declare class DecisionError extends Error {
|
|
19
|
+
constructor(message: string);
|
|
20
|
+
}
|
|
21
|
+
export declare function decide(request: DecisionRequest, env?: NodeJS.ProcessEnv): Promise<Decision>;
|
package/dist/decide.js
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* One Decision API call. A missing key, a transport failure, a redirect, or
|
|
3
|
+
* any outcome other than allow is a block. This client has no offline path:
|
|
4
|
+
* it never returns a synthetic allow.
|
|
5
|
+
*/
|
|
6
|
+
import { randomUUID } from "node:crypto";
|
|
7
|
+
const DEFAULT_BASE = "https://app.cognexuslabs.ai";
|
|
8
|
+
const TIMEOUT_MS = 10_000;
|
|
9
|
+
export class DecisionError extends Error {
|
|
10
|
+
constructor(message) {
|
|
11
|
+
super(message);
|
|
12
|
+
this.name = "DecisionError";
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
function failureKind(err) {
|
|
16
|
+
if (err && typeof err === "object") {
|
|
17
|
+
const named = err;
|
|
18
|
+
const name = named.name && named.name !== "Error" ? named.name : "";
|
|
19
|
+
const code = named.code ?? "";
|
|
20
|
+
const kind = [name, code].filter(Boolean).join(" ");
|
|
21
|
+
if (kind)
|
|
22
|
+
return kind;
|
|
23
|
+
}
|
|
24
|
+
return "Error";
|
|
25
|
+
}
|
|
26
|
+
function reasonsOf(value) {
|
|
27
|
+
if (!Array.isArray(value))
|
|
28
|
+
return [];
|
|
29
|
+
return value.filter((item) => typeof item === "string");
|
|
30
|
+
}
|
|
31
|
+
export async function decide(request, env = process.env) {
|
|
32
|
+
const key = env.COGNEXUS_API_KEY ?? "";
|
|
33
|
+
if (key.trim() === "") {
|
|
34
|
+
throw new DecisionError("No API key configured. Set COGNEXUS_API_KEY.");
|
|
35
|
+
}
|
|
36
|
+
const base = (env.COGNEXUS_API_BASE_URL ?? DEFAULT_BASE).replace(/\/+$/, "");
|
|
37
|
+
const url = `${base}/api/v1/decisions`;
|
|
38
|
+
const controller = new AbortController();
|
|
39
|
+
const timer = setTimeout(() => controller.abort(), TIMEOUT_MS);
|
|
40
|
+
let response;
|
|
41
|
+
try {
|
|
42
|
+
response = await fetch(url, {
|
|
43
|
+
method: "POST",
|
|
44
|
+
redirect: "manual",
|
|
45
|
+
signal: controller.signal,
|
|
46
|
+
headers: {
|
|
47
|
+
"content-type": "application/json",
|
|
48
|
+
"x-api-key": key,
|
|
49
|
+
},
|
|
50
|
+
body: JSON.stringify({
|
|
51
|
+
agent_did: request.agentId,
|
|
52
|
+
action: request.action,
|
|
53
|
+
target: request.target,
|
|
54
|
+
payload: request.payload,
|
|
55
|
+
payload_kind: "tool_call",
|
|
56
|
+
surface: "mcp",
|
|
57
|
+
request_id: request.requestId ?? randomUUID(),
|
|
58
|
+
product: "artzain-mcp-gateway@0.1.0",
|
|
59
|
+
}),
|
|
60
|
+
});
|
|
61
|
+
}
|
|
62
|
+
catch (err) {
|
|
63
|
+
throw new DecisionError(`decision unavailable (${failureKind(err)}). Failing closed.`);
|
|
64
|
+
}
|
|
65
|
+
finally {
|
|
66
|
+
clearTimeout(timer);
|
|
67
|
+
}
|
|
68
|
+
if (response.status >= 300 && response.status < 400) {
|
|
69
|
+
throw new DecisionError("decision unavailable (redirect). Failing closed.");
|
|
70
|
+
}
|
|
71
|
+
if (!response.ok) {
|
|
72
|
+
throw new DecisionError(`decision unavailable (HTTP ${response.status}). Failing closed.`);
|
|
73
|
+
}
|
|
74
|
+
let body;
|
|
75
|
+
try {
|
|
76
|
+
body = await response.json();
|
|
77
|
+
}
|
|
78
|
+
catch {
|
|
79
|
+
throw new DecisionError("decision unavailable (bad response). Failing closed.");
|
|
80
|
+
}
|
|
81
|
+
if (!body || typeof body !== "object") {
|
|
82
|
+
throw new DecisionError("decision unavailable (bad response). Failing closed.");
|
|
83
|
+
}
|
|
84
|
+
const row = body;
|
|
85
|
+
if (typeof row.outcome !== "string" || row.outcome === "") {
|
|
86
|
+
throw new DecisionError("decision unavailable (no outcome). Failing closed.");
|
|
87
|
+
}
|
|
88
|
+
return {
|
|
89
|
+
outcome: row.outcome,
|
|
90
|
+
decisionId: typeof row.decision_id === "string" ? row.decision_id : "",
|
|
91
|
+
reasons: reasonsOf(row.reasons),
|
|
92
|
+
};
|
|
93
|
+
}
|
package/dist/server.d.ts
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The gateway speaks MCP on stdin and stdout. A tools/call is forwarded only
|
|
3
|
+
* when the Decision API returns allow. Every other outcome, including an
|
|
4
|
+
* outage, is isError and the upstream is not called.
|
|
5
|
+
*/
|
|
6
|
+
import { type GatewayConfig } from "./config.js";
|
|
7
|
+
export declare class Gateway {
|
|
8
|
+
private readonly config;
|
|
9
|
+
private readonly sessions;
|
|
10
|
+
constructor(config: GatewayConfig);
|
|
11
|
+
listTools(): Promise<unknown>;
|
|
12
|
+
callTool(name: string, args: unknown): Promise<unknown>;
|
|
13
|
+
close(): void;
|
|
14
|
+
private route;
|
|
15
|
+
private session;
|
|
16
|
+
}
|
|
17
|
+
interface RpcRequest {
|
|
18
|
+
jsonrpc?: string;
|
|
19
|
+
id?: number | string | null;
|
|
20
|
+
method?: string;
|
|
21
|
+
params?: unknown;
|
|
22
|
+
}
|
|
23
|
+
export declare function handleRequest(gateway: Gateway, request: RpcRequest): Promise<string | undefined>;
|
|
24
|
+
export declare function serve(config: GatewayConfig, input: NodeJS.ReadableStream, output: NodeJS.WritableStream): Promise<void>;
|
|
25
|
+
export declare function run(argv: string[]): Promise<number>;
|
|
26
|
+
export {};
|
package/dist/server.js
ADDED
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The gateway speaks MCP on stdin and stdout. A tools/call is forwarded only
|
|
3
|
+
* when the Decision API returns allow. Every other outcome, including an
|
|
4
|
+
* outage, is isError and the upstream is not called.
|
|
5
|
+
*/
|
|
6
|
+
import { createInterface } from "node:readline";
|
|
7
|
+
import { ConfigError, loadConfig } from "./config.js";
|
|
8
|
+
import { decide, DecisionError } from "./decide.js";
|
|
9
|
+
import { classifyTool } from "./taxonomy.js";
|
|
10
|
+
import { openUpstream, UpstreamError } from "./upstream.js";
|
|
11
|
+
const PROTOCOL = "2024-11-05";
|
|
12
|
+
function textResult(text, isError) {
|
|
13
|
+
return { content: [{ type: "text", text }], isError };
|
|
14
|
+
}
|
|
15
|
+
function stringArgs(value) {
|
|
16
|
+
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
17
|
+
return {};
|
|
18
|
+
const out = {};
|
|
19
|
+
for (const [key, item] of Object.entries(value)) {
|
|
20
|
+
if (typeof item === "string" || typeof item === "number" || typeof item === "boolean") {
|
|
21
|
+
out[key] = String(item);
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
return out;
|
|
25
|
+
}
|
|
26
|
+
function refusal(decision) {
|
|
27
|
+
const id = decision.decisionId ? `\n(decision ${decision.decisionId})` : "";
|
|
28
|
+
if (decision.outcome === "review") {
|
|
29
|
+
return `QUEUED FOR REVIEW: this call needs human approval before it runs.${id}`;
|
|
30
|
+
}
|
|
31
|
+
if (decision.outcome === "deny") {
|
|
32
|
+
const reasons = decision.reasons.length > 0 ? decision.reasons.join("; ") : "policy denied this call";
|
|
33
|
+
return `REFUSED: ${reasons}${id}`;
|
|
34
|
+
}
|
|
35
|
+
return `REFUSED: unrecognised outcome ${JSON.stringify(decision.outcome)}. Failing closed.${id}`;
|
|
36
|
+
}
|
|
37
|
+
export class Gateway {
|
|
38
|
+
config;
|
|
39
|
+
sessions = new Map();
|
|
40
|
+
constructor(config) {
|
|
41
|
+
this.config = config;
|
|
42
|
+
}
|
|
43
|
+
async listTools() {
|
|
44
|
+
const tools = [];
|
|
45
|
+
for (const upstream of this.config.upstreams) {
|
|
46
|
+
let listed;
|
|
47
|
+
try {
|
|
48
|
+
listed = await this.session(upstream).then((session) => session.listTools());
|
|
49
|
+
}
|
|
50
|
+
catch (err) {
|
|
51
|
+
const kind = err instanceof UpstreamError ? err.message : "the upstream could not be listed";
|
|
52
|
+
throw new UpstreamError(`upstream ${upstream.name}: ${kind}`);
|
|
53
|
+
}
|
|
54
|
+
for (const tool of listed) {
|
|
55
|
+
if (!tool || typeof tool !== "object")
|
|
56
|
+
continue;
|
|
57
|
+
const row = tool;
|
|
58
|
+
if (typeof row.name !== "string" || row.name === "")
|
|
59
|
+
continue;
|
|
60
|
+
tools.push({
|
|
61
|
+
name: `${upstream.name}__${row.name}`,
|
|
62
|
+
description: typeof row.description === "string" ? row.description : "",
|
|
63
|
+
inputSchema: row.inputSchema ?? { type: "object" },
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
return { tools };
|
|
68
|
+
}
|
|
69
|
+
async callTool(name, args) {
|
|
70
|
+
const routed = this.route(name);
|
|
71
|
+
if (!routed)
|
|
72
|
+
return textResult(`Unknown tool ${JSON.stringify(name)}.`, true);
|
|
73
|
+
const override = routed.upstream.tools[routed.tool];
|
|
74
|
+
const classified = classifyTool(routed.tool, stringArgs(args));
|
|
75
|
+
const action = override || classified.action;
|
|
76
|
+
const payload = JSON.stringify({ tool: action, arguments: args ?? {} });
|
|
77
|
+
let decision;
|
|
78
|
+
try {
|
|
79
|
+
decision = await decide({
|
|
80
|
+
agentId: routed.upstream.agentId,
|
|
81
|
+
action,
|
|
82
|
+
target: classified.target,
|
|
83
|
+
payload,
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
catch (err) {
|
|
87
|
+
const message = err instanceof DecisionError ? err.message : "decision unavailable (Error). Failing closed.";
|
|
88
|
+
return textResult(`REFUSED: ${message}`, true);
|
|
89
|
+
}
|
|
90
|
+
if (decision.outcome !== "allow")
|
|
91
|
+
return textResult(refusal(decision), true);
|
|
92
|
+
try {
|
|
93
|
+
const session = await this.session(routed.upstream);
|
|
94
|
+
const result = await session.callTool(routed.tool, args ?? {});
|
|
95
|
+
if (result && typeof result === "object")
|
|
96
|
+
return result;
|
|
97
|
+
return textResult("the upstream returned an empty result", true);
|
|
98
|
+
}
|
|
99
|
+
catch (err) {
|
|
100
|
+
const message = err instanceof UpstreamError ? err.message : "the upstream call failed";
|
|
101
|
+
return textResult(`FAILED: ${message}`, true);
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
close() {
|
|
105
|
+
for (const session of this.sessions.values())
|
|
106
|
+
session.close();
|
|
107
|
+
this.sessions.clear();
|
|
108
|
+
}
|
|
109
|
+
route(name) {
|
|
110
|
+
const upstream = this.config.upstreams.find((row) => name.startsWith(`${row.name}__`));
|
|
111
|
+
if (!upstream)
|
|
112
|
+
return undefined;
|
|
113
|
+
const tool = name.slice(upstream.name.length + 2);
|
|
114
|
+
if (tool === "")
|
|
115
|
+
return undefined;
|
|
116
|
+
return { upstream, tool };
|
|
117
|
+
}
|
|
118
|
+
async session(upstream) {
|
|
119
|
+
const existing = this.sessions.get(upstream.name);
|
|
120
|
+
if (existing)
|
|
121
|
+
return existing;
|
|
122
|
+
const opened = openUpstream(upstream);
|
|
123
|
+
try {
|
|
124
|
+
await opened.start();
|
|
125
|
+
}
|
|
126
|
+
catch (err) {
|
|
127
|
+
opened.close();
|
|
128
|
+
throw err;
|
|
129
|
+
}
|
|
130
|
+
this.sessions.set(upstream.name, opened);
|
|
131
|
+
return opened;
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
function reply(id, result) {
|
|
135
|
+
return `${JSON.stringify({ jsonrpc: "2.0", id: id ?? null, result })}\n`;
|
|
136
|
+
}
|
|
137
|
+
function fail(id, code, message) {
|
|
138
|
+
return `${JSON.stringify({ jsonrpc: "2.0", id: id ?? null, error: { code, message } })}\n`;
|
|
139
|
+
}
|
|
140
|
+
export async function handleRequest(gateway, request) {
|
|
141
|
+
const { id, method, params } = request;
|
|
142
|
+
if (method === "notifications/initialized" || method === "notifications/cancelled")
|
|
143
|
+
return undefined;
|
|
144
|
+
if (id === undefined)
|
|
145
|
+
return undefined;
|
|
146
|
+
if (method === "initialize") {
|
|
147
|
+
return reply(id, {
|
|
148
|
+
protocolVersion: PROTOCOL,
|
|
149
|
+
capabilities: { tools: {} },
|
|
150
|
+
serverInfo: { name: "artzain-mcp-gateway", version: "0.1.0" },
|
|
151
|
+
});
|
|
152
|
+
}
|
|
153
|
+
if (method === "ping")
|
|
154
|
+
return reply(id, {});
|
|
155
|
+
if (method === "tools/list") {
|
|
156
|
+
try {
|
|
157
|
+
return reply(id, await gateway.listTools());
|
|
158
|
+
}
|
|
159
|
+
catch (err) {
|
|
160
|
+
const message = err instanceof UpstreamError ? err.message : "the tool list failed";
|
|
161
|
+
return fail(id, -32000, message);
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
if (method === "tools/call") {
|
|
165
|
+
const row = (params ?? {});
|
|
166
|
+
if (typeof row.name !== "string")
|
|
167
|
+
return fail(id, -32602, "tools/call needs a tool name");
|
|
168
|
+
return reply(id, await gateway.callTool(row.name, row.arguments));
|
|
169
|
+
}
|
|
170
|
+
return fail(id, -32601, "Method not found");
|
|
171
|
+
}
|
|
172
|
+
export async function serve(config, input, output) {
|
|
173
|
+
const gateway = new Gateway(config);
|
|
174
|
+
const stop = () => gateway.close();
|
|
175
|
+
process.on("SIGINT", stop);
|
|
176
|
+
process.on("SIGTERM", stop);
|
|
177
|
+
process.on("exit", stop);
|
|
178
|
+
const lines = createInterface({ input });
|
|
179
|
+
for await (const line of lines) {
|
|
180
|
+
const trimmed = line.trim();
|
|
181
|
+
if (!trimmed)
|
|
182
|
+
continue;
|
|
183
|
+
let request;
|
|
184
|
+
try {
|
|
185
|
+
request = JSON.parse(trimmed);
|
|
186
|
+
}
|
|
187
|
+
catch {
|
|
188
|
+
output.write(fail(null, -32700, "Parse error"));
|
|
189
|
+
continue;
|
|
190
|
+
}
|
|
191
|
+
const response = await handleRequest(gateway, request);
|
|
192
|
+
if (response)
|
|
193
|
+
output.write(response);
|
|
194
|
+
}
|
|
195
|
+
gateway.close();
|
|
196
|
+
}
|
|
197
|
+
export async function run(argv) {
|
|
198
|
+
if (argv.includes("--help") || argv.includes("-h")) {
|
|
199
|
+
process.stdout.write("artzain-mcp-gateway --config gateway.json\n");
|
|
200
|
+
return 0;
|
|
201
|
+
}
|
|
202
|
+
const flag = argv.indexOf("--config");
|
|
203
|
+
const path = flag >= 0 ? argv[flag + 1] : process.env.ARTZAIN_GATEWAY_CONFIG || "gateway.json";
|
|
204
|
+
if (!path) {
|
|
205
|
+
process.stderr.write("a config path is required\n");
|
|
206
|
+
return 2;
|
|
207
|
+
}
|
|
208
|
+
let config;
|
|
209
|
+
try {
|
|
210
|
+
config = loadConfig(path);
|
|
211
|
+
}
|
|
212
|
+
catch (err) {
|
|
213
|
+
const message = err instanceof ConfigError ? err.message : "cannot read the gateway config";
|
|
214
|
+
process.stderr.write(`${message}\n`);
|
|
215
|
+
return 2;
|
|
216
|
+
}
|
|
217
|
+
await serve(config, process.stdin, process.stdout);
|
|
218
|
+
return 0;
|
|
219
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The W15 tool taxonomy: a connector tool name becomes one action and one
|
|
3
|
+
* target. The action is what a policy rule matches. The target is
|
|
4
|
+
* `<system>:<kind>/<id>`, for example `slack:channel/C123` or
|
|
5
|
+
* `github:repo/acme/inventory`.
|
|
6
|
+
*/
|
|
7
|
+
export declare const UNKNOWN_ACTION = "unknown_tool";
|
|
8
|
+
export interface ClassifiedTool {
|
|
9
|
+
action: string;
|
|
10
|
+
target: string;
|
|
11
|
+
known: boolean;
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* The action and target for a connector tool name. `args` fills the id in
|
|
15
|
+
* the target template. An unknown name is `unknown_tool` and
|
|
16
|
+
* `unknown:tool/<name>`.
|
|
17
|
+
*/
|
|
18
|
+
export declare function classifyTool(name: string, args?: Record<string, string>): ClassifiedTool;
|
package/dist/taxonomy.js
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The W15 tool taxonomy: a connector tool name becomes one action and one
|
|
3
|
+
* target. The action is what a policy rule matches. The target is
|
|
4
|
+
* `<system>:<kind>/<id>`, for example `slack:channel/C123` or
|
|
5
|
+
* `github:repo/acme/inventory`.
|
|
6
|
+
*/
|
|
7
|
+
import { readFileSync } from "node:fs";
|
|
8
|
+
import { dirname, join } from "node:path";
|
|
9
|
+
import { fileURLToPath } from "node:url";
|
|
10
|
+
export const UNKNOWN_ACTION = "unknown_tool";
|
|
11
|
+
let cached;
|
|
12
|
+
function readTaxonomy() {
|
|
13
|
+
if (cached)
|
|
14
|
+
return cached;
|
|
15
|
+
const here = dirname(fileURLToPath(import.meta.url));
|
|
16
|
+
const candidates = [join(here, "taxonomy.json"), join(here, "..", "src", "taxonomy.json")];
|
|
17
|
+
for (const path of candidates) {
|
|
18
|
+
try {
|
|
19
|
+
const parsed = JSON.parse(readFileSync(path, "utf8"));
|
|
20
|
+
if (!parsed || !Array.isArray(parsed.actions) || !parsed.tools) {
|
|
21
|
+
cached = { problem: "taxonomy.json is not a tool map" };
|
|
22
|
+
return cached;
|
|
23
|
+
}
|
|
24
|
+
cached = parsed;
|
|
25
|
+
return cached;
|
|
26
|
+
}
|
|
27
|
+
catch (err) {
|
|
28
|
+
const code = err.code;
|
|
29
|
+
if (code !== "ENOENT") {
|
|
30
|
+
cached = { problem: code ?? "unreadable" };
|
|
31
|
+
return cached;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
cached = { problem: "ENOENT" };
|
|
36
|
+
return cached;
|
|
37
|
+
}
|
|
38
|
+
function fill(template, args) {
|
|
39
|
+
const filled = template.replace(/\{([A-Za-z0-9_]+)\}/g, (_match, key) => args[key] ?? "");
|
|
40
|
+
return filled.replace(/\/+$/, "");
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* The action and target for a connector tool name. `args` fills the id in
|
|
44
|
+
* the target template. An unknown name is `unknown_tool` and
|
|
45
|
+
* `unknown:tool/<name>`.
|
|
46
|
+
*/
|
|
47
|
+
export function classifyTool(name, args = {}) {
|
|
48
|
+
const taxonomy = readTaxonomy();
|
|
49
|
+
const raw = name.trim();
|
|
50
|
+
if ("problem" in taxonomy) {
|
|
51
|
+
return { action: UNKNOWN_ACTION, target: `unknown:tool/${raw}`, known: false };
|
|
52
|
+
}
|
|
53
|
+
const row = taxonomy.tools[raw.toLowerCase()];
|
|
54
|
+
if (!row) {
|
|
55
|
+
return { action: UNKNOWN_ACTION, target: `unknown:tool/${raw}`, known: false };
|
|
56
|
+
}
|
|
57
|
+
return { action: row.action, target: fill(row.target, args), known: true };
|
|
58
|
+
}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
{
|
|
2
|
+
"actions": [
|
|
3
|
+
"send_email",
|
|
4
|
+
"send_chat_message",
|
|
5
|
+
"send_agent_message",
|
|
6
|
+
"post_public",
|
|
7
|
+
"create_ticket",
|
|
8
|
+
"update_ticket",
|
|
9
|
+
"create_event",
|
|
10
|
+
"update_event",
|
|
11
|
+
"purchase",
|
|
12
|
+
"delete_resource",
|
|
13
|
+
"share_resource",
|
|
14
|
+
"write_file",
|
|
15
|
+
"run_command",
|
|
16
|
+
"write_repo",
|
|
17
|
+
"publish_package",
|
|
18
|
+
"submit_form",
|
|
19
|
+
"unknown_tool"
|
|
20
|
+
],
|
|
21
|
+
"tools": {
|
|
22
|
+
"send_email": { "action": "send_email", "target": "email:mailbox/{to}" },
|
|
23
|
+
"gmail_send_email": { "action": "send_email", "target": "gmail:message/{to}" },
|
|
24
|
+
"outlook_send_mail": { "action": "send_email", "target": "outlook:message/{to}" },
|
|
25
|
+
"compose_email": { "action": "send_email", "target": "email:mailbox/{to}" },
|
|
26
|
+
"slack_send_message": { "action": "send_chat_message", "target": "slack:channel/{channel}" },
|
|
27
|
+
"slack_post_message": { "action": "send_chat_message", "target": "slack:channel/{channel}" },
|
|
28
|
+
"post_message": { "action": "send_chat_message", "target": "slack:channel/{channel}" },
|
|
29
|
+
"teams_post_message": { "action": "send_chat_message", "target": "teams:channel/{channel}" },
|
|
30
|
+
"send_sms": { "action": "send_chat_message", "target": "sms:number/{to}" },
|
|
31
|
+
"send_chat_message": { "action": "send_chat_message", "target": "chat:channel/{channel}" },
|
|
32
|
+
"send_agent_message": { "action": "send_agent_message", "target": "agent:bot/{to}" },
|
|
33
|
+
"post_to_x": { "action": "post_public", "target": "x:post/{account}" },
|
|
34
|
+
"tweet": { "action": "post_public", "target": "x:post/{account}" },
|
|
35
|
+
"post_to_linkedin": { "action": "post_public", "target": "linkedin:post/{author}" },
|
|
36
|
+
"post_public": { "action": "post_public", "target": "web:post/{account}" },
|
|
37
|
+
"create_ticket": { "action": "create_ticket", "target": "ticket:issue/{title}" },
|
|
38
|
+
"jira_create_issue": { "action": "create_ticket", "target": "jira:issue/{project}" },
|
|
39
|
+
"update_ticket": { "action": "update_ticket", "target": "ticket:issue/{id}" },
|
|
40
|
+
"jira_update_issue": { "action": "update_ticket", "target": "jira:issue/{issue}" },
|
|
41
|
+
"create_event": { "action": "create_event", "target": "calendar:event/{calendar}" },
|
|
42
|
+
"gcal_create_event": { "action": "create_event", "target": "google:event/{calendar}" },
|
|
43
|
+
"update_event": { "action": "update_event", "target": "calendar:event/{event_id}" },
|
|
44
|
+
"purchase": { "action": "purchase", "target": "payment:order/{sku}" },
|
|
45
|
+
"place_order": { "action": "purchase", "target": "payment:order/{sku}" },
|
|
46
|
+
"checkout": { "action": "purchase", "target": "payment:order/{cart}" },
|
|
47
|
+
"pay_invoice": { "action": "purchase", "target": "payment:invoice/{invoice_id}" },
|
|
48
|
+
"wire_transfer": { "action": "purchase", "target": "bank:transfer/{account}" },
|
|
49
|
+
"delete_resource": { "action": "delete_resource", "target": "resource:item/{id}" },
|
|
50
|
+
"delete_file": { "action": "delete_resource", "target": "file:path/{path}" },
|
|
51
|
+
"share_resource": { "action": "share_resource", "target": "drive:file/{file}" },
|
|
52
|
+
"share_file": { "action": "share_resource", "target": "drive:file/{file}" },
|
|
53
|
+
"write_file": { "action": "write_file", "target": "file:path/{path}" },
|
|
54
|
+
"run_command": { "action": "run_command", "target": "shell:host/{host}" },
|
|
55
|
+
"execute_command": { "action": "run_command", "target": "shell:host/{host}" },
|
|
56
|
+
"write_repo": { "action": "write_repo", "target": "github:repo/{repo}" },
|
|
57
|
+
"github_create_pr": { "action": "write_repo", "target": "github:repo/{repo}" },
|
|
58
|
+
"publish_package": { "action": "publish_package", "target": "registry:package/{name}" },
|
|
59
|
+
"npm_publish": { "action": "publish_package", "target": "npm:package/{name}" },
|
|
60
|
+
"submit_form": { "action": "submit_form", "target": "form:page/{url}" }
|
|
61
|
+
}
|
|
62
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* One upstream MCP session, over a child process or an HTTP POST.
|
|
3
|
+
* Stderr from a child, and response headers from an HTTP server, can carry
|
|
4
|
+
* a token. This module reads them only to keep the pipes moving, and it
|
|
5
|
+
* never writes them out.
|
|
6
|
+
*/
|
|
7
|
+
import type { UpstreamConfig } from "./config.js";
|
|
8
|
+
export interface RpcMessage {
|
|
9
|
+
jsonrpc?: string;
|
|
10
|
+
id?: number | string | null;
|
|
11
|
+
method?: string;
|
|
12
|
+
params?: unknown;
|
|
13
|
+
result?: unknown;
|
|
14
|
+
error?: {
|
|
15
|
+
code?: number;
|
|
16
|
+
message?: string;
|
|
17
|
+
};
|
|
18
|
+
}
|
|
19
|
+
export declare class UpstreamError extends Error {
|
|
20
|
+
constructor(message: string);
|
|
21
|
+
}
|
|
22
|
+
export declare class StdioUpstream {
|
|
23
|
+
private child;
|
|
24
|
+
private pending;
|
|
25
|
+
private nextId;
|
|
26
|
+
private readonly command;
|
|
27
|
+
private readonly env;
|
|
28
|
+
constructor(config: UpstreamConfig);
|
|
29
|
+
start(): Promise<void>;
|
|
30
|
+
listTools(): Promise<unknown[]>;
|
|
31
|
+
callTool(name: string, args: unknown): Promise<unknown>;
|
|
32
|
+
close(): void;
|
|
33
|
+
private notify;
|
|
34
|
+
private request;
|
|
35
|
+
private takeLine;
|
|
36
|
+
private failAll;
|
|
37
|
+
}
|
|
38
|
+
export declare class HttpUpstream {
|
|
39
|
+
private session;
|
|
40
|
+
private nextId;
|
|
41
|
+
private started;
|
|
42
|
+
private readonly url;
|
|
43
|
+
private readonly headers;
|
|
44
|
+
constructor(config: UpstreamConfig);
|
|
45
|
+
start(): Promise<void>;
|
|
46
|
+
listTools(): Promise<unknown[]>;
|
|
47
|
+
callTool(name: string, args: unknown): Promise<unknown>;
|
|
48
|
+
close(): void;
|
|
49
|
+
private request;
|
|
50
|
+
private post;
|
|
51
|
+
}
|
|
52
|
+
export type Upstream = StdioUpstream | HttpUpstream;
|
|
53
|
+
export declare function openUpstream(config: UpstreamConfig): Upstream;
|
package/dist/upstream.js
ADDED
|
@@ -0,0 +1,229 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* One upstream MCP session, over a child process or an HTTP POST.
|
|
3
|
+
* Stderr from a child, and response headers from an HTTP server, can carry
|
|
4
|
+
* a token. This module reads them only to keep the pipes moving, and it
|
|
5
|
+
* never writes them out.
|
|
6
|
+
*/
|
|
7
|
+
import { spawn } from "node:child_process";
|
|
8
|
+
import { createInterface } from "node:readline";
|
|
9
|
+
const PROTOCOL = "2024-11-05";
|
|
10
|
+
const CLIENT = { name: "artzain-mcp-gateway", version: "0.1.0" };
|
|
11
|
+
export class UpstreamError extends Error {
|
|
12
|
+
constructor(message) {
|
|
13
|
+
super(message);
|
|
14
|
+
this.name = "UpstreamError";
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
function childEnv(extra) {
|
|
18
|
+
const env = {};
|
|
19
|
+
for (const key of ["PATH", "Path", "PATHEXT", "SYSTEMROOT", "SystemRoot", "COMSPEC", "HOME", "USERPROFILE", "TEMP", "TMP"]) {
|
|
20
|
+
const value = process.env[key];
|
|
21
|
+
if (value)
|
|
22
|
+
env[key] = value;
|
|
23
|
+
}
|
|
24
|
+
for (const [key, value] of Object.entries(extra))
|
|
25
|
+
env[key] = value;
|
|
26
|
+
return env;
|
|
27
|
+
}
|
|
28
|
+
export class StdioUpstream {
|
|
29
|
+
child;
|
|
30
|
+
pending = new Map();
|
|
31
|
+
nextId = 1;
|
|
32
|
+
command;
|
|
33
|
+
env;
|
|
34
|
+
constructor(config) {
|
|
35
|
+
this.command = config.command ?? [];
|
|
36
|
+
this.env = config.env ?? {};
|
|
37
|
+
}
|
|
38
|
+
async start() {
|
|
39
|
+
if (this.child)
|
|
40
|
+
return;
|
|
41
|
+
const [file, ...args] = this.command;
|
|
42
|
+
if (!file)
|
|
43
|
+
throw new UpstreamError("the upstream command is empty");
|
|
44
|
+
const child = spawn(file, args, { stdio: ["pipe", "pipe", "pipe"], env: childEnv(this.env), windowsHide: true });
|
|
45
|
+
this.child = child;
|
|
46
|
+
child.stderr.on("data", () => undefined);
|
|
47
|
+
child.on("error", (err) => this.failAll(new UpstreamError(`the upstream process failed (${err.name})`)));
|
|
48
|
+
child.on("exit", () => this.failAll(new UpstreamError("the upstream process exited")));
|
|
49
|
+
const lines = createInterface({ input: child.stdout });
|
|
50
|
+
lines.on("line", (line) => this.takeLine(line));
|
|
51
|
+
await this.request("initialize", {
|
|
52
|
+
protocolVersion: PROTOCOL,
|
|
53
|
+
capabilities: {},
|
|
54
|
+
clientInfo: CLIENT,
|
|
55
|
+
});
|
|
56
|
+
this.notify("notifications/initialized");
|
|
57
|
+
}
|
|
58
|
+
async listTools() {
|
|
59
|
+
const result = await this.request("tools/list", {});
|
|
60
|
+
const tools = result.tools;
|
|
61
|
+
if (!Array.isArray(tools))
|
|
62
|
+
throw new UpstreamError("the upstream tools list is not an array");
|
|
63
|
+
return tools;
|
|
64
|
+
}
|
|
65
|
+
async callTool(name, args) {
|
|
66
|
+
return this.request("tools/call", { name, arguments: args ?? {} });
|
|
67
|
+
}
|
|
68
|
+
close() {
|
|
69
|
+
this.child?.kill();
|
|
70
|
+
this.child = undefined;
|
|
71
|
+
}
|
|
72
|
+
notify(method) {
|
|
73
|
+
this.child?.stdin.write(`${JSON.stringify({ jsonrpc: "2.0", method })}\n`);
|
|
74
|
+
}
|
|
75
|
+
request(method, params) {
|
|
76
|
+
const child = this.child;
|
|
77
|
+
if (!child)
|
|
78
|
+
return Promise.reject(new UpstreamError("the upstream is not running"));
|
|
79
|
+
const id = this.nextId;
|
|
80
|
+
this.nextId += 1;
|
|
81
|
+
return new Promise((resolve, reject) => {
|
|
82
|
+
const timer = setTimeout(() => {
|
|
83
|
+
this.pending.delete(id);
|
|
84
|
+
reject(new UpstreamError("the upstream timed out"));
|
|
85
|
+
}, 10_000);
|
|
86
|
+
this.pending.set(id, {
|
|
87
|
+
resolve: (message) => {
|
|
88
|
+
clearTimeout(timer);
|
|
89
|
+
if (message.error) {
|
|
90
|
+
const code = message.error.code ?? -1;
|
|
91
|
+
reject(new UpstreamError(`the upstream rejected the call (${code})`));
|
|
92
|
+
return;
|
|
93
|
+
}
|
|
94
|
+
resolve(message.result);
|
|
95
|
+
},
|
|
96
|
+
reject: (err) => {
|
|
97
|
+
clearTimeout(timer);
|
|
98
|
+
reject(err);
|
|
99
|
+
},
|
|
100
|
+
});
|
|
101
|
+
child.stdin.write(`${JSON.stringify({ jsonrpc: "2.0", id, method, params })}\n`);
|
|
102
|
+
});
|
|
103
|
+
}
|
|
104
|
+
takeLine(line) {
|
|
105
|
+
const trimmed = line.trim();
|
|
106
|
+
if (!trimmed)
|
|
107
|
+
return;
|
|
108
|
+
let message;
|
|
109
|
+
try {
|
|
110
|
+
message = JSON.parse(trimmed);
|
|
111
|
+
}
|
|
112
|
+
catch {
|
|
113
|
+
return;
|
|
114
|
+
}
|
|
115
|
+
if (typeof message.id !== "number")
|
|
116
|
+
return;
|
|
117
|
+
const waiter = this.pending.get(message.id);
|
|
118
|
+
if (!waiter)
|
|
119
|
+
return;
|
|
120
|
+
this.pending.delete(message.id);
|
|
121
|
+
waiter.resolve(message);
|
|
122
|
+
}
|
|
123
|
+
failAll(err) {
|
|
124
|
+
for (const waiter of this.pending.values())
|
|
125
|
+
waiter.reject(err);
|
|
126
|
+
this.pending.clear();
|
|
127
|
+
this.child = undefined;
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
export class HttpUpstream {
|
|
131
|
+
session;
|
|
132
|
+
nextId = 1;
|
|
133
|
+
started = false;
|
|
134
|
+
url;
|
|
135
|
+
headers;
|
|
136
|
+
constructor(config) {
|
|
137
|
+
this.url = config.url ?? "";
|
|
138
|
+
this.headers = config.headers ?? {};
|
|
139
|
+
}
|
|
140
|
+
async start() {
|
|
141
|
+
if (this.started)
|
|
142
|
+
return;
|
|
143
|
+
await this.request("initialize", {
|
|
144
|
+
protocolVersion: PROTOCOL,
|
|
145
|
+
capabilities: {},
|
|
146
|
+
clientInfo: CLIENT,
|
|
147
|
+
});
|
|
148
|
+
await this.post({ jsonrpc: "2.0", method: "notifications/initialized" });
|
|
149
|
+
this.started = true;
|
|
150
|
+
}
|
|
151
|
+
async listTools() {
|
|
152
|
+
const result = await this.request("tools/list", {});
|
|
153
|
+
const tools = result.tools;
|
|
154
|
+
if (!Array.isArray(tools))
|
|
155
|
+
throw new UpstreamError("the upstream tools list is not an array");
|
|
156
|
+
return tools;
|
|
157
|
+
}
|
|
158
|
+
async callTool(name, args) {
|
|
159
|
+
return this.request("tools/call", { name, arguments: args ?? {} });
|
|
160
|
+
}
|
|
161
|
+
close() {
|
|
162
|
+
this.started = false;
|
|
163
|
+
}
|
|
164
|
+
async request(method, params) {
|
|
165
|
+
const id = this.nextId;
|
|
166
|
+
this.nextId += 1;
|
|
167
|
+
const message = await this.post({ jsonrpc: "2.0", id, method, params });
|
|
168
|
+
if (message.error) {
|
|
169
|
+
const code = message.error.code ?? -1;
|
|
170
|
+
throw new UpstreamError(`the upstream rejected the call (${code})`);
|
|
171
|
+
}
|
|
172
|
+
return message.result;
|
|
173
|
+
}
|
|
174
|
+
async post(body) {
|
|
175
|
+
const headers = {
|
|
176
|
+
"content-type": "application/json",
|
|
177
|
+
accept: "application/json, text/event-stream",
|
|
178
|
+
...this.headers,
|
|
179
|
+
};
|
|
180
|
+
if (this.session)
|
|
181
|
+
headers["mcp-session-id"] = this.session;
|
|
182
|
+
const controller = new AbortController();
|
|
183
|
+
const timer = setTimeout(() => controller.abort(), 10_000);
|
|
184
|
+
let response;
|
|
185
|
+
try {
|
|
186
|
+
response = await fetch(this.url, {
|
|
187
|
+
method: "POST",
|
|
188
|
+
redirect: "manual",
|
|
189
|
+
signal: controller.signal,
|
|
190
|
+
headers,
|
|
191
|
+
body: JSON.stringify(body),
|
|
192
|
+
});
|
|
193
|
+
}
|
|
194
|
+
catch (err) {
|
|
195
|
+
const name = err && typeof err === "object" && "name" in err ? String(err.name) : "Error";
|
|
196
|
+
throw new UpstreamError(`the upstream is unreachable (${name})`);
|
|
197
|
+
}
|
|
198
|
+
finally {
|
|
199
|
+
clearTimeout(timer);
|
|
200
|
+
}
|
|
201
|
+
if (response.status >= 300 && response.status < 400) {
|
|
202
|
+
throw new UpstreamError("the upstream redirected the call");
|
|
203
|
+
}
|
|
204
|
+
const session = response.headers.get("mcp-session-id");
|
|
205
|
+
if (session)
|
|
206
|
+
this.session = session;
|
|
207
|
+
if (!response.ok) {
|
|
208
|
+
throw new UpstreamError(`the upstream rejected the call (HTTP ${response.status})`);
|
|
209
|
+
}
|
|
210
|
+
const type = response.headers.get("content-type") ?? "";
|
|
211
|
+
const text = await response.text();
|
|
212
|
+
const payload = type.includes("text/event-stream")
|
|
213
|
+
? text.split("\n").find((line) => line.startsWith("data: "))?.slice(6)
|
|
214
|
+
: text;
|
|
215
|
+
if (body.id === undefined && !type.includes("text/event-stream"))
|
|
216
|
+
return {};
|
|
217
|
+
if (!payload)
|
|
218
|
+
throw new UpstreamError("the upstream returned an empty event stream");
|
|
219
|
+
try {
|
|
220
|
+
return JSON.parse(payload);
|
|
221
|
+
}
|
|
222
|
+
catch {
|
|
223
|
+
throw new UpstreamError("the upstream returned a response that is not JSON");
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
export function openUpstream(config) {
|
|
228
|
+
return config.command ? new StdioUpstream(config) : new HttpUpstream(config);
|
|
229
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,41 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cognexuslabs/artzain-mcp-gateway",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "An MCP server that decides each upstream tool call with the ArtzAIn Decision API before it forwards the call.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"license": "Apache-2.0",
|
|
7
|
+
"engines": {
|
|
8
|
+
"node": ">=18"
|
|
9
|
+
},
|
|
10
|
+
"bin": {
|
|
11
|
+
"artzain-mcp-gateway": "./dist/cli.js"
|
|
12
|
+
},
|
|
13
|
+
"files": [
|
|
14
|
+
"dist/",
|
|
15
|
+
"README.md",
|
|
16
|
+
"LICENSE",
|
|
17
|
+
"CHANGELOG.md"
|
|
18
|
+
],
|
|
19
|
+
"publishConfig": {
|
|
20
|
+
"access": "public"
|
|
21
|
+
},
|
|
22
|
+
"repository": {
|
|
23
|
+
"type": "git",
|
|
24
|
+
"url": "git+https://github.com/CogNEXUSlabs/cognexus-tools.git",
|
|
25
|
+
"directory": "mcp-gateway"
|
|
26
|
+
},
|
|
27
|
+
"homepage": "https://cognexuslabs.ai",
|
|
28
|
+
"bugs": {
|
|
29
|
+
"url": "https://github.com/CogNEXUSlabs/cognexus-tools/issues"
|
|
30
|
+
},
|
|
31
|
+
"scripts": {
|
|
32
|
+
"build": "tsc -p tsconfig.json && node scripts/copy-taxonomy.mjs",
|
|
33
|
+
"test": "vitest run",
|
|
34
|
+
"prepublishOnly": "npm run build && npm test"
|
|
35
|
+
},
|
|
36
|
+
"devDependencies": {
|
|
37
|
+
"@types/node": "^26.2.0",
|
|
38
|
+
"typescript": "^7.0.2",
|
|
39
|
+
"vitest": "^5.0.0"
|
|
40
|
+
}
|
|
41
|
+
}
|