@pauhu/mcp 0.0.0-stage → 3.0.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/README.md +22 -2
- package/bridge.mjs +251 -0
- package/cli.mjs +2 -0
- package/package.json +14 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this 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 Pauhu AI Ltd
|
|
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,23 @@
|
|
|
1
|
-
#
|
|
1
|
+
# pauhu
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Machines ask, Pauhu answers with the source. Try free, pay per result.
|
|
4
|
+
|
|
5
|
+
Connect any MCP client to Pauhu. Every answer carries its source, or says plainly that none was found.
|
|
6
|
+
|
|
7
|
+
## Use
|
|
8
|
+
|
|
9
|
+
```json
|
|
10
|
+
{
|
|
11
|
+
"mcpServers": {
|
|
12
|
+
"pauhu": { "command": "npx", "args": ["-y", "@pauhu/mcp"] }
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
On first use you sign in with your browser. Or set `PAUHU_TOKEN` to a key from https://pauhu.eu/account.
|
|
18
|
+
|
|
19
|
+
Prices per delivered result: https://api.pauhu.ai/v1/lds/outputs
|
|
20
|
+
|
|
21
|
+
## Licence
|
|
22
|
+
|
|
23
|
+
Apache-2.0, Pauhu AI Ltd. https://pauhu.ai
|
package/bridge.mjs
ADDED
|
@@ -0,0 +1,251 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pauhu MCP bridge (thin client). Licensed under Apache-2.0; (c) Pauhu AI Ltd, https://pauhu.ai
|
|
3
|
+
*
|
|
4
|
+
* This bundle holds no tool logic, prompt or resource text. Tools, prompts and resources are
|
|
5
|
+
* forwarded over StreamableHTTP to the Pauhu MCP service at PAUHU_MCP_URL, which runs them; what
|
|
6
|
+
* the service lists appears here at once, with no bundle rebuild.
|
|
7
|
+
*
|
|
8
|
+
* Auth: PAUHU_TOKEN, else PAUHU_REFRESH_TOKEN exchanged at auth.pauhu.ai, else OAuth Device Flow.
|
|
9
|
+
* Sign-in is lazy: the stdio server answers initialize at once, and the first request starts the
|
|
10
|
+
* sign-in, waits a bounded time, and otherwise returns the sign-in link as the error so the host
|
|
11
|
+
* can show it. Every credential the bridge holds is redacted from any text it writes and from
|
|
12
|
+
* every result it passes on; sign-in links must be on the auth origin.
|
|
13
|
+
*
|
|
14
|
+
* Retry: list/read/get requests are read-only and are retried once after any failure. tools/call
|
|
15
|
+
* is retried once only when the service cannot have run it: the connect step failed, or the service
|
|
16
|
+
* answered 401 (refresh, then retry) or 404 (session expired, re-initialize). Any other failure
|
|
17
|
+
* after the request was sent is returned, never replayed. A 401 refreshes only when it answered the
|
|
18
|
+
* current token; a late 401 for an older token just retries. A JSON-RPC error the service answered
|
|
19
|
+
* is final: it is passed on with its code, not retried.
|
|
20
|
+
*/
|
|
21
|
+
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
|
22
|
+
import { StreamableHTTPClientTransport, StreamableHTTPError } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
|
|
23
|
+
import { UnauthorizedError } from "@modelcontextprotocol/sdk/client/auth.js";
|
|
24
|
+
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
|
|
25
|
+
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
26
|
+
import { CallToolRequestSchema, ErrorCode, GetPromptRequestSchema, ListPromptsRequestSchema, ListResourcesRequestSchema, ListResourceTemplatesRequestSchema, ListToolsRequestSchema, McpError, ReadResourceRequestSchema } from "@modelcontextprotocol/sdk/types.js";
|
|
27
|
+
|
|
28
|
+
const AUTH_URL = process.env.PAUHU_AUTH_URL ?? "https://auth.pauhu.ai/realms/pauhu";
|
|
29
|
+
const CLIENT_ID = process.env.PAUHU_CLIENT_ID ?? "pauhu-mcpb";
|
|
30
|
+
const MCP_URL = process.env.PAUHU_MCP_URL ?? "https://api.pauhu.ai/mcp";
|
|
31
|
+
const CALL_MS = Number(process.env.PAUHU_CALL_TIMEOUT_MS ?? 120_000);
|
|
32
|
+
const AUTH_MS = 15_000; // one token or device-code HTTP call
|
|
33
|
+
const WAIT_MS = 45_000; // how long one request waits for a browser sign-in in progress
|
|
34
|
+
const VERSION = "3.0.5";
|
|
35
|
+
|
|
36
|
+
// An omitted optional user_config can arrive as the literal "${user_config.x}"; that is no value.
|
|
37
|
+
const given = (v) => (v && !v.startsWith("${") ? v : null);
|
|
38
|
+
|
|
39
|
+
class BridgeError extends Error {} // message is fixed text written here, safe to show as is
|
|
40
|
+
|
|
41
|
+
const withTimeout = (p, ms, msg) => Promise.race([
|
|
42
|
+
p,
|
|
43
|
+
new Promise((_, rej) => { const t = setTimeout(() => rej(new BridgeError(typeof msg === "function" ? msg() : msg)), ms); t.unref?.(); }),
|
|
44
|
+
]);
|
|
45
|
+
|
|
46
|
+
const held = new Set(); // every access or refresh token this process has held
|
|
47
|
+
let token = null, refreshToken = null;
|
|
48
|
+
const setToken = (t) => { token = t || null; if (token) held.add(token); return token; };
|
|
49
|
+
const setRefresh = (t) => { refreshToken = t || null; if (refreshToken) held.add(refreshToken); };
|
|
50
|
+
setToken(given(process.env.PAUHU_TOKEN));
|
|
51
|
+
setRefresh(given(process.env.PAUHU_REFRESH_TOKEN));
|
|
52
|
+
|
|
53
|
+
function redact(s) {
|
|
54
|
+
let out = String(s ?? "");
|
|
55
|
+
for (const v of held) out = out.split(v).join("[redacted]");
|
|
56
|
+
return out
|
|
57
|
+
.replace(/eyJ[\w-]+\.[\w-]+\.[\w-]*/g, "[redacted]")
|
|
58
|
+
.replace(/(authorization|access_token|refresh_token|id_token|token)(["':=\s]+)(?:bearer\s+)?[^\s"',}&]+/gi, "$1$2[redacted]")
|
|
59
|
+
.replace(/\bbearer\s+[^\s"',}&]+/gi, "Bearer [redacted]")
|
|
60
|
+
.slice(0, 500);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
// Results pass through unchanged except that any credential this process has held is replaced in every string,
|
|
64
|
+
// object keys included (R4 review: a credential could ride out as a structuredContent key).
|
|
65
|
+
function scrub(v) {
|
|
66
|
+
if (typeof v === "string") { let out = v; for (const t of held) out = out.split(t).join("[redacted]"); return out; }
|
|
67
|
+
if (Array.isArray(v)) return v.map(scrub);
|
|
68
|
+
if (v && typeof v === "object") return Object.fromEntries(Object.entries(v).map(([k, x]) => [scrub(k), scrub(x)]));
|
|
69
|
+
return v;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// Text shown to the user must hold no credential, also once percent-decoded.
|
|
73
|
+
function clean(s) {
|
|
74
|
+
let d = null;
|
|
75
|
+
try { d = decodeURIComponent(s); } catch { /* malformed escape */ }
|
|
76
|
+
return d !== null && redact(s) === s && redact(d) === d;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
async function post(path, params) {
|
|
80
|
+
const r = await fetch(`${AUTH_URL}/protocol/openid-connect/${path}`, {
|
|
81
|
+
method: "POST",
|
|
82
|
+
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
|
83
|
+
body: new URLSearchParams({ client_id: CLIENT_ID, ...params }),
|
|
84
|
+
signal: AbortSignal.timeout(AUTH_MS),
|
|
85
|
+
});
|
|
86
|
+
return { status: r.status, body: await r.json().catch(() => ({})) };
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
const UNREACHABLE = "Pauhu sign-in service unreachable; check the connection and try again";
|
|
90
|
+
|
|
91
|
+
let refreshing = null; // one refresh at a time; callers share its result
|
|
92
|
+
function refresh() {
|
|
93
|
+
if (!refreshToken) return Promise.resolve(null);
|
|
94
|
+
return (refreshing ??= post("token", { grant_type: "refresh_token", refresh_token: refreshToken })
|
|
95
|
+
.then((t) => {
|
|
96
|
+
if (t.status === 200 && t.body.access_token) {
|
|
97
|
+
if (t.body.refresh_token) setRefresh(t.body.refresh_token);
|
|
98
|
+
return setToken(t.body.access_token);
|
|
99
|
+
}
|
|
100
|
+
if (t.status === 400 || t.status === 401) { setRefresh(null); return null; } // refused: never present it again
|
|
101
|
+
throw new BridgeError(UNREACHABLE);
|
|
102
|
+
}, () => { throw new BridgeError(UNREACHABLE); })
|
|
103
|
+
.finally(() => { refreshing = null; }));
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function signInLink(d) { // only a link on the auth origin, holding no credential, is shown
|
|
107
|
+
let u = null;
|
|
108
|
+
try { u = new URL(d.verification_uri_complete ?? d.verification_uri); } catch { /* not a URL */ }
|
|
109
|
+
const code = String(d.user_code ?? "").replace(/[^A-Za-z0-9-]/g, "").slice(0, 16);
|
|
110
|
+
const shown = !u ? null : d.verification_uri_complete ? u.href : `${u.href} (code ${code})`;
|
|
111
|
+
if (!u || u.origin !== new URL(AUTH_URL).origin || u.username || u.password || !clean(shown))
|
|
112
|
+
throw new BridgeError("Pauhu sign-in returned an unexpected link; try again");
|
|
113
|
+
return shown;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
let signIn = null, signInUrl = null; // one device flow at a time; refresh token kept in memory only
|
|
117
|
+
function deviceFlow() {
|
|
118
|
+
return (signIn ??= (async () => {
|
|
119
|
+
const dc = await post("auth/device", { scope: "openid offline_access" }).catch(() => { throw new BridgeError(UNREACHABLE); });
|
|
120
|
+
if (dc.status !== 200 || !dc.body.device_code) throw new BridgeError(`Pauhu sign-in could not start (HTTP ${dc.status})`);
|
|
121
|
+
const d = dc.body;
|
|
122
|
+
signInUrl = signInLink(d);
|
|
123
|
+
process.stderr.write(`\nPauhu: open this URL to sign in:\n ${signInUrl}\n`);
|
|
124
|
+
const deadline = Date.now() + Math.min(d.expires_in ?? 300, 1800) * 1000;
|
|
125
|
+
let wait = Math.max(d.interval ?? 5, 1) * 1000;
|
|
126
|
+
while (Date.now() < deadline) {
|
|
127
|
+
await new Promise((r) => setTimeout(r, wait));
|
|
128
|
+
const t = await post("token", { grant_type: "urn:ietf:params:oauth:grant-type:device_code", device_code: d.device_code })
|
|
129
|
+
.catch(() => ({ status: 0, body: { error: "authorization_pending" } }));
|
|
130
|
+
if (t.status === 200 && t.body.access_token) {
|
|
131
|
+
setRefresh(t.body.refresh_token);
|
|
132
|
+
process.stderr.write("Pauhu: signed in.\n");
|
|
133
|
+
return setToken(t.body.access_token);
|
|
134
|
+
}
|
|
135
|
+
if (t.body.error === "slow_down") wait += 5000;
|
|
136
|
+
else if (t.body.error !== "authorization_pending") throw new BridgeError("Pauhu sign-in was refused; try again");
|
|
137
|
+
}
|
|
138
|
+
throw new BridgeError("Pauhu sign-in timed out; try again to get a new sign-in link");
|
|
139
|
+
})().finally(() => { signIn = null; signInUrl = null; }));
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
async function ensureToken() {
|
|
143
|
+
if (token) return token;
|
|
144
|
+
if (await refresh()) return token;
|
|
145
|
+
const flow = deviceFlow();
|
|
146
|
+
flow.catch(() => {}); // a later request reports the outcome; never an unhandled rejection
|
|
147
|
+
return withTimeout(flow, WAIT_MS, () => "Pauhu sign-in is waiting for you: open " + (signInUrl ?? "the link shown by the extension") +
|
|
148
|
+
" and then try again"); // built at the deadline, once the device flow has set the URL
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
let conn = null; // promise of the one upstream client; shared by concurrent requests
|
|
152
|
+
function client() {
|
|
153
|
+
if (conn) return conn;
|
|
154
|
+
const mine = (async () => {
|
|
155
|
+
const bearer = await ensureToken();
|
|
156
|
+
const c = new Client({ name: "pauhu-mcpb", version: VERSION }, { capabilities: {} });
|
|
157
|
+
try {
|
|
158
|
+
await withTimeout(c.connect(new StreamableHTTPClientTransport(new URL(MCP_URL), {
|
|
159
|
+
requestInit: { headers: { Authorization: `Bearer ${bearer}` } },
|
|
160
|
+
})), 60_000, "Pauhu service did not answer in time");
|
|
161
|
+
} catch (e) {
|
|
162
|
+
try { await c.close(); } catch { /* not open */ }
|
|
163
|
+
throw Object.assign(e, { connectPhase: true, bearer });
|
|
164
|
+
}
|
|
165
|
+
return Object.assign(c, { bearer, inflight: 0 }); // the token this connection sends, for 401 handling
|
|
166
|
+
})();
|
|
167
|
+
conn = mine;
|
|
168
|
+
mine.catch(() => { if (conn === mine) conn = null; });
|
|
169
|
+
return mine;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
async function drop(failed) { // retire only the client that failed, never a newer one; it closes
|
|
173
|
+
if (conn !== failed) return; // when no request is in flight on it, so a concurrent call sharing
|
|
174
|
+
conn = null; // it is never cut off mid-flight (R4: "Connection closed" race)
|
|
175
|
+
const c = await failed.catch(() => null);
|
|
176
|
+
if (c) { c.retired = true; if (!c.inflight) c.close().catch(() => {}); }
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
async function on(c, fn) { // run one request on client c, counted in flight for drop()
|
|
180
|
+
c.inflight++;
|
|
181
|
+
try { return await fn(c); } finally { if (!--c.inflight && c.retired) c.close().catch(() => {}); }
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
const status = (e) => (e instanceof UnauthorizedError ? 401 : e instanceof StreamableHTTPError && e.code > 0 ? e.code : null);
|
|
185
|
+
|
|
186
|
+
function publicMessage(e) {
|
|
187
|
+
if (e instanceof BridgeError) return e.message;
|
|
188
|
+
const s = status(e);
|
|
189
|
+
if (s === 401 || s === 403) return "Pauhu sign-in expired or not permitted; restart the Pauhu extension to sign in again";
|
|
190
|
+
if (s) return `Pauhu service error (HTTP ${s})`;
|
|
191
|
+
if (e instanceof McpError) return redact(e.message); // the Pauhu server's own JSON-RPC error, e.g. an unknown tool
|
|
192
|
+
return "Pauhu service unreachable; check the connection and try again";
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
async function forward(fn, readOnly) {
|
|
196
|
+
const used = client();
|
|
197
|
+
let first, bearer = null;
|
|
198
|
+
try {
|
|
199
|
+
const c = await used;
|
|
200
|
+
bearer = c.bearer;
|
|
201
|
+
return await on(c, fn);
|
|
202
|
+
} catch (e) {
|
|
203
|
+
first = e;
|
|
204
|
+
}
|
|
205
|
+
const s = status(first);
|
|
206
|
+
const lost = [ErrorCode.ConnectionClosed, ErrorCode.RequestTimeout]; // no answer arrived: a transport fault
|
|
207
|
+
const answered = first instanceof McpError && !lost.includes(first.code);
|
|
208
|
+
const safe = !(first instanceof BridgeError) && !answered && (readOnly || first.connectPhase || s === 401 || s === 404);
|
|
209
|
+
if (!safe) throw first;
|
|
210
|
+
if (s === 401 && (first.bearer ?? bearer) === token) { // refused the current token: refresh once (a refused refresh
|
|
211
|
+
token = null; // token is dropped, so the retry goes to browser sign-in)
|
|
212
|
+
await refresh();
|
|
213
|
+
}
|
|
214
|
+
await drop(used);
|
|
215
|
+
return await on(await client(), fn);
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
const server = new Server({ name: "pauhu", version: VERSION }, { capabilities: { tools: {}, resources: {}, prompts: {} } });
|
|
219
|
+
|
|
220
|
+
const offers = (c, cap) => Boolean(c.getServerCapabilities()?.[cap]);
|
|
221
|
+
const READ = [ // read-only: forwarded, retried once after any failure
|
|
222
|
+
[ListToolsRequestSchema, (c, p) => c.listTools(p)],
|
|
223
|
+
[ListResourcesRequestSchema, (c, p) => (offers(c, "resources") ? c.listResources(p) : { resources: [] })],
|
|
224
|
+
[ListResourceTemplatesRequestSchema, (c, p) => (offers(c, "resources") ? c.listResourceTemplates(p) : { resourceTemplates: [] })],
|
|
225
|
+
[ReadResourceRequestSchema, (c, p) => c.readResource(p)],
|
|
226
|
+
[ListPromptsRequestSchema, (c, p) => (offers(c, "prompts") ? c.listPrompts(p) : { prompts: [] })],
|
|
227
|
+
[GetPromptRequestSchema, (c, p) => c.getPrompt(p)],
|
|
228
|
+
];
|
|
229
|
+
for (const [schema, op] of READ) {
|
|
230
|
+
server.setRequestHandler(schema, async (req) => {
|
|
231
|
+
try {
|
|
232
|
+
return scrub(await forward((c) => withTimeout(op(c, req.params), 60_000, "Pauhu service did not answer in time"), true));
|
|
233
|
+
} catch (e) {
|
|
234
|
+
if (e instanceof McpError && status(e) === null) // the server's own answer: keep its code, drop its data; a plain
|
|
235
|
+
throw Object.assign(new Error(redact(e.message.replace(/^(MCP error -?\d+: )+/, ""))), { code: e.code }); // Error, so the prefix is added once
|
|
236
|
+
throw new Error(publicMessage(e)); // the SDK sends it as JSON-RPC InternalError
|
|
237
|
+
}
|
|
238
|
+
});
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
server.setRequestHandler(CallToolRequestSchema, async (req) => {
|
|
242
|
+
try {
|
|
243
|
+
return scrub(await forward((c) => withTimeout(c.callTool(req.params), CALL_MS, "Pauhu tool call timed out"), false));
|
|
244
|
+
} catch (e) {
|
|
245
|
+
return { content: [{ type: "text", text: JSON.stringify({ error: publicMessage(e) }) }], isError: true };
|
|
246
|
+
}
|
|
247
|
+
});
|
|
248
|
+
|
|
249
|
+
await server.connect(new StdioServerTransport());
|
|
250
|
+
// The SDK stdio transport ignores end of input; exit when the host closes stdin, so no sign-in poll or held token outlives it.
|
|
251
|
+
process.stdin.on("end", () => process.exit(0));
|
package/cli.mjs
ADDED
package/package.json
CHANGED
|
@@ -1,6 +1,16 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@pauhu/mcp",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "3.0.5",
|
|
4
|
+
"description": "Pauhu: sourced answers over MCP. Every answer carries its source or says plainly it found none.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"license": "Apache-2.0",
|
|
7
|
+
"author": "Pauhu AI Ltd (https://pauhu.ai)",
|
|
8
|
+
"homepage": "https://pauhu.ai",
|
|
9
|
+
"keywords": ["mcp", "model-context-protocol", "sourced-answers", "citations", "eu-law", "translation"],
|
|
10
|
+
"bin": { "pauhu": "cli.mjs" },
|
|
11
|
+
"main": "bridge.mjs",
|
|
12
|
+
"files": ["bridge.mjs", "cli.mjs", "LICENSE", "README.md"],
|
|
13
|
+
"dependencies": { "@modelcontextprotocol/sdk": "1.32.1" },
|
|
14
|
+
"engines": { "node": ">=18" },
|
|
15
|
+
"mcpName": "ai.pauhu/mcp"
|
|
16
|
+
}
|