@lynq/lynq 0.4.0 → 0.6.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.
Files changed (49) hide show
  1. package/dist/adapters/express.d.ts +7 -2
  2. package/dist/adapters/express.mjs +2 -2
  3. package/dist/adapters/hono.d.ts +7 -2
  4. package/dist/adapters/hono.mjs +1 -1
  5. package/dist/chunk-BVDKAIOU.mjs +1 -0
  6. package/dist/chunk-INAAPNKG.mjs +1 -0
  7. package/dist/chunk-OJJZGR4B.mjs +170 -0
  8. package/dist/chunk-OYHVJKUP.mjs +1 -0
  9. package/dist/chunk-SPZY5GJA.mjs +1 -0
  10. package/dist/index.d.ts +5 -7
  11. package/dist/index.mjs +1 -1
  12. package/dist/middleware/auth.d.ts +1 -1
  13. package/dist/middleware/bearer.d.ts +1 -1
  14. package/dist/middleware/combine.d.ts +1 -1
  15. package/dist/middleware/credentials.d.ts +1 -1
  16. package/dist/middleware/crypto.d.ts +64 -0
  17. package/dist/middleware/crypto.mjs +2 -0
  18. package/dist/middleware/github.d.ts +54 -0
  19. package/dist/middleware/github.mjs +2 -0
  20. package/dist/middleware/google.d.ts +55 -0
  21. package/dist/middleware/google.mjs +2 -0
  22. package/dist/middleware/guard.d.ts +1 -1
  23. package/dist/middleware/jwt.d.ts +1 -1
  24. package/dist/middleware/logger.d.ts +1 -1
  25. package/dist/middleware/oauth.d.ts +8 -2
  26. package/dist/middleware/oauth.mjs +1 -1
  27. package/dist/middleware/payment.d.ts +8 -2
  28. package/dist/middleware/payment.mjs +1 -1
  29. package/dist/middleware/rate-limit.d.ts +1 -1
  30. package/dist/middleware/stripe.d.ts +60 -0
  31. package/dist/middleware/stripe.mjs +1 -0
  32. package/dist/middleware/tip.d.ts +15 -0
  33. package/dist/middleware/tip.mjs +4 -0
  34. package/dist/middleware/truncate.d.ts +1 -1
  35. package/dist/middleware/url-action.d.ts +8 -2
  36. package/dist/middleware/url-action.mjs +1 -1
  37. package/dist/pages-IPpN74gp.d.ts +26 -0
  38. package/dist/pages-VK55ZBAP.mjs +1 -0
  39. package/dist/store.d.ts +9 -0
  40. package/dist/store.mjs +1 -0
  41. package/dist/test.d.ts +1 -1
  42. package/dist/{types-CqT2idkd.d.ts → types-BdFjg9Tn.d.ts} +20 -1
  43. package/package.json +38 -5
  44. package/dist/chunk-2KEVF6YL.mjs +0 -1
  45. package/dist/chunk-STWVQGX5.mjs +0 -1
  46. package/dist/middleware/github-oauth.d.ts +0 -42
  47. package/dist/middleware/github-oauth.mjs +0 -2
  48. package/dist/middleware/google-oauth.d.ts +0 -43
  49. package/dist/middleware/google-oauth.mjs +0 -2
@@ -1,5 +1,6 @@
1
1
  import { Express } from 'express';
2
- import { M as MCPServer } from '../types-CqT2idkd.js';
2
+ import { M as MCPServer } from '../types-BdFjg9Tn.js';
3
+ import { P as PagesConfig } from '../pages-IPpN74gp.js';
3
4
  import '@modelcontextprotocol/sdk/types.js';
4
5
  import 'zod';
5
6
 
@@ -8,7 +9,11 @@ interface MountOptions {
8
9
  path?: string;
9
10
  /** Allowed hostnames for DNS rebinding protection. Default: localhost variants. */
10
11
  allowedHosts?: string[];
12
+ /** Enable default pages for specified auth/payment providers. */
13
+ pages?: PagesConfig;
14
+ /** URL prefix for pages routes. Default: "/lynq" */
15
+ pagesPrefix?: string;
11
16
  }
12
17
  declare function mountLynq(app: Express, server: MCPServer, options?: MountOptions): void;
13
18
 
14
- export { type MountOptions, mountLynq };
19
+ export { type MountOptions, PagesConfig, mountLynq };
@@ -1,2 +1,2 @@
1
- import {b,a}from'../chunk-7C4A572Z.mjs';function u(e){let t=e.protocol||"http",s=e.headers.host||"localhost",o=`${t}://${s}${e.originalUrl}`,r=new Headers;for(let[a,n]of Object.entries(e.headers))n&&r.set(a,Array.isArray(n)?n.join(", "):n);let i={method:e.method,headers:r};return e.method!=="GET"&&e.method!=="HEAD"&&(i.body=JSON.stringify(e.body)),new Request(o,i)}async function h(e,t){if(e.status(t.status),t.headers.forEach((s,o)=>e.setHeader(o,s)),t.body){let s=t.body.getReader();try{for(;;){let{done:o,value:r}=await s.read();if(o)break;e.write(r);}}finally{e.end();}}else e.end();}function y(e,t,s){let o=s?.path??"/mcp",r=t.http(),i=s?.allowedHosts??[...b];e.use(o,(a$1,n,d)=>{if(!a(a$1.headers.host??null,i)){n.status(403).json({jsonrpc:"2.0",error:{code:-32e3,message:"Forbidden"},id:null});return}d();}),e.all(o,async(a,n)=>{let d=u(a),p=await r(d);await h(n,p);});}
2
- export{y as mountLynq};
1
+ import {b,a}from'../chunk-7C4A572Z.mjs';import {b as b$1}from'../chunk-OJJZGR4B.mjs';function p(e){let g=e.protocol||"http",u=e.headers.host||"localhost",r=`${g}://${u}${e.originalUrl}`,n=new Headers;for(let[t,s]of Object.entries(e.headers))s&&n.set(t,Array.isArray(s)?s.join(", "):s);let a={method:e.method,headers:n};return e.method!=="GET"&&e.method!=="HEAD"&&(a.body=JSON.stringify(e.body)),new Request(r,a)}async function h(e,g){if(e.status(g.status),g.headers.forEach((u,r)=>e.setHeader(r,u)),g.body){let u=g.body.getReader();try{for(;;){let{done:r,value:n}=await u.read();if(r)break;e.write(n);}}finally{e.end();}}else e.end();}function P(e,g,u){let r=u?.path??"/mcp",n=g.http(),a$1=u?.allowedHosts??[...b];e.use(r,(t,s,i)=>{if(!a(t.headers.host??null,a$1)){s.status(403).json({jsonrpc:"2.0",error:{code:-32e3,message:"Forbidden"},id:null});return}i();}),e.all(r,async(t,s)=>{let i=p(t),o=await n(i);await h(s,o);}),u?.pages&&m(e,g,u);}function d(e){let g=e.protocol||"http",u=e.headers.host||"localhost";return `${g}://${u}`}function m(e,g,u){let r=u.pagesPrefix??"/lynq",n=u.pages;if(n.github&&typeof n.github!="string"){let a=n.github;e.get(`${r}/auth/github/callback`,async(t,s)=>{let{handleGitHubPage:i}=await import('../pages-VK55ZBAP.mjs'),o=await i(g,{code:t.query.code,state:t.query.state},a,r);if(o.redirect)return s.redirect(o.redirect);s.status(o.status).send(o.html);});}else if(typeof n.github=="string"){let a=n.github;e.get(`${r}/auth/github/callback`,(t,s)=>{let i=new URL(a,d(t));for(let[o,c]of Object.entries(t.query))typeof c=="string"&&i.searchParams.set(o,c);s.redirect(i.toString());});}if(n.google&&typeof n.google!="string"){let a=n.google;e.get(`${r}/auth/google/callback`,async(t,s)=>{let{handleGooglePage:i}=await import('../pages-VK55ZBAP.mjs'),o=`${d(t)}${r}/auth/google/callback`,c=await i(g,{code:t.query.code,state:t.query.state},a,r,o);if(c.redirect)return s.redirect(c.redirect);s.status(c.status).send(c.html);});}else if(typeof n.google=="string"){let a=n.google;e.get(`${r}/auth/google/callback`,(t,s)=>{let i=new URL(a,d(t));for(let[o,c]of Object.entries(t.query))typeof c=="string"&&i.searchParams.set(o,c);s.redirect(i.toString());});}if(n.stripe&&typeof n.stripe!="string"){let a=n.stripe;e.get(`${r}/payment/stripe/callback`,async(t,s)=>{let{handleStripePage:i}=await import('../pages-VK55ZBAP.mjs'),o=await i(g,{session_id:t.query.session_id,cancelled:t.query.cancelled,state:t.query.state},a,r);if(o.redirect)return s.redirect(o.redirect);s.status(o.status).send(o.html);});}else if(typeof n.stripe=="string"){let a=n.stripe;e.get(`${r}/payment/stripe/callback`,(t,s)=>{let i=new URL(a,d(t));for(let[o,c]of Object.entries(t.query))typeof c=="string"&&i.searchParams.set(o,c);s.redirect(i.toString());});}if(n.crypto&&typeof n.crypto!="string"){let a=n.crypto;e.get(`${r}/payment/crypto`,async(t,s)=>{let{handleCryptoGet:i}=await import('../pages-VK55ZBAP.mjs'),o=`${d(t)}${r}/payment/crypto/callback`,c=i({recipient:t.query.recipient,amount:t.query.amount,token:t.query.token,network:t.query.network,state:t.query.state},o);s.status(c.status).send(c.html);}),e.post(`${r}/payment/crypto/callback`,async(t,s)=>{let{handleCryptoPost:i}=await import('../pages-VK55ZBAP.mjs'),o=await i(g,t.body,a);s.status(o.status).json(o.json);});}else if(typeof n.crypto=="string"){let a=n.crypto;e.get(`${r}/payment/crypto`,(t,s)=>{let i=new URL(a,d(t));for(let[o,c]of Object.entries(t.query))typeof c=="string"&&i.searchParams.set(o,c);s.redirect(i.toString());});}e.get(`${r}/auth/success`,(a,t)=>{t.send(b$1("Authentication"));}),e.get(`${r}/payment/success`,(a,t)=>{t.send(b$1("Payment"));});}
2
+ export{P as mountLynq};
@@ -1,5 +1,6 @@
1
1
  import { Hono } from 'hono';
2
- import { M as MCPServer } from '../types-CqT2idkd.js';
2
+ import { M as MCPServer } from '../types-BdFjg9Tn.js';
3
+ import { P as PagesConfig } from '../pages-IPpN74gp.js';
3
4
  import '@modelcontextprotocol/sdk/types.js';
4
5
  import 'zod';
5
6
 
@@ -8,7 +9,11 @@ interface MountOptions {
8
9
  path?: string;
9
10
  /** Allowed hostnames for DNS rebinding protection. Default: localhost variants. */
10
11
  allowedHosts?: string[];
12
+ /** Enable default pages for specified auth/payment providers. */
13
+ pages?: PagesConfig;
14
+ /** URL prefix for pages routes. Default: "/lynq" */
15
+ pagesPrefix?: string;
11
16
  }
12
17
  declare function mountLynq(app: Hono, server: MCPServer, options?: MountOptions): void;
13
18
 
14
- export { type MountOptions, mountLynq };
19
+ export { type MountOptions, PagesConfig, mountLynq };
@@ -1 +1 @@
1
- import {b,a}from'../chunk-7C4A572Z.mjs';function m(t,a$1,e){let r=e?.path??"/mcp",l=a$1.http(),i=e?.allowedHosts??[...b];t.use(r,async(o,p)=>a(o.req.header("host")??null,i)?p():o.json({jsonrpc:"2.0",error:{code:-32e3,message:"Forbidden"},id:null},403)),t.all(r,o=>l(o.req.raw));}export{m as mountLynq};
1
+ import {b,a}from'../chunk-7C4A572Z.mjs';import {b as b$1}from'../chunk-OJJZGR4B.mjs';function q(a$1,u,c){let s=c?.path??"/mcp",o=u.http(),t=c?.allowedHosts??[...b];a$1.use(s,async(e,r)=>a(e.req.header("host")??null,t)?r():e.json({jsonrpc:"2.0",error:{code:-32e3,message:"Forbidden"},id:null},403)),a$1.all(s,e=>o(e.req.raw)),c?.pages&&f(a$1,u,c);}function f(a,u,c){let s=c.pagesPrefix??"/lynq",o=c.pages;if(o.github&&typeof o.github!="string"?a.get(`${s}/auth/github/callback`,async t=>{let{handleGitHubPage:e}=await import('../pages-VK55ZBAP.mjs'),r=await e(u,{code:t.req.query("code"),state:t.req.query("state")},o.github,s);return r.redirect?t.redirect(r.redirect):t.html(r.html??"",r.status)}):typeof o.github=="string"&&a.get(`${s}/auth/github/callback`,t=>{let e=new URL(o.github,t.req.url),r=t.req.query();for(let[i,n]of Object.entries(r))e.searchParams.set(i,n);return t.redirect(e.toString())}),o.google&&typeof o.google!="string"?a.get(`${s}/auth/google/callback`,async t=>{let{handleGooglePage:e}=await import('../pages-VK55ZBAP.mjs'),i=`${new URL(t.req.url).origin}${s}/auth/google/callback`,n=await e(u,{code:t.req.query("code"),state:t.req.query("state")},o.google,s,i);return n.redirect?t.redirect(n.redirect):t.html(n.html??"",n.status)}):typeof o.google=="string"&&a.get(`${s}/auth/google/callback`,t=>{let e=new URL(o.google,t.req.url),r=t.req.query();for(let[i,n]of Object.entries(r))e.searchParams.set(i,n);return t.redirect(e.toString())}),o.stripe&&typeof o.stripe!="string"?a.get(`${s}/payment/stripe/callback`,async t=>{let{handleStripePage:e}=await import('../pages-VK55ZBAP.mjs'),r=await e(u,{session_id:t.req.query("session_id"),cancelled:t.req.query("cancelled"),state:t.req.query("state")},o.stripe,s);return r.redirect?t.redirect(r.redirect):t.html(r.html??"",r.status)}):typeof o.stripe=="string"&&a.get(`${s}/payment/stripe/callback`,t=>{let e=new URL(o.stripe,t.req.url),r=t.req.query();for(let[i,n]of Object.entries(r))e.searchParams.set(i,n);return t.redirect(e.toString())}),o.crypto&&typeof o.crypto!="string"){let t=o.crypto;a.get(`${s}/payment/crypto`,async e=>{let{handleCryptoGet:r}=await import('../pages-VK55ZBAP.mjs'),i=`${new URL(e.req.url).origin}${s}/payment/crypto/callback`,n=r({recipient:e.req.query("recipient"),amount:e.req.query("amount"),token:e.req.query("token"),network:e.req.query("network"),state:e.req.query("state")},i);return e.html(n.html??"",n.status)}),a.post(`${s}/payment/crypto/callback`,async e=>{let{handleCryptoPost:r}=await import('../pages-VK55ZBAP.mjs'),i=await e.req.json(),n=await r(u,i,t);return e.json(n.json,n.status)});}else typeof o.crypto=="string"&&a.get(`${s}/payment/crypto`,t=>{let e=new URL(o.crypto,t.req.url),r=t.req.query();for(let[i,n]of Object.entries(r))e.searchParams.set(i,n);return t.redirect(e.toString())});a.get(`${s}/auth/success`,t=>t.html(b$1("Authentication"))),a.get(`${s}/payment/success`,t=>t.html(b$1("Payment")));}export{q as mountLynq};
@@ -0,0 +1 @@
1
+ import {a}from'./chunk-OYHVJKUP.mjs';function s(e){let t={name:e.name??"payment",sessionKey:e.sessionKey??"payment",message:e.message??"Please complete payment to continue.",buildUrl:e.buildUrl,declineMessage:"Payment cancelled."};return e.timeout!==void 0&&(t.timeout=e.timeout),e.persistent!==void 0&&(t.persistent=e.persistent),e.skipIf&&(t.skipIf=e.skipIf),e.onComplete&&(t.onComplete=e.onComplete),a(t)}export{s as a};
@@ -0,0 +1 @@
1
+ import {a}from'./chunk-OYHVJKUP.mjs';function n(e){let t={name:e.name??"oauth",sessionKey:e.sessionKey??"user",message:e.message??"Please sign in to continue.",buildUrl:e.buildUrl,declineMessage:"Authentication cancelled."};return e.timeout!==void 0&&(t.timeout=e.timeout),e.persistent!==void 0&&(t.persistent=e.persistent),e.skipIf&&(t.skipIf=e.skipIf),e.onComplete&&(t.onComplete=e.onComplete),a(t)}export{n as a};
@@ -0,0 +1,170 @@
1
+ function c(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function u(e){let t=c(e);return `<!DOCTYPE html>
2
+ <html>
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <title>${t} Complete</title>
6
+ <style>
7
+ body { font-family: system-ui, sans-serif; display: flex; justify-content: center; align-items: center; min-height: 100vh; margin: 0; color: #1a1a1a; }
8
+ .card { text-align: center; padding: 40px; }
9
+ .check { font-size: 3em; margin-bottom: 12px; }
10
+ h1 { font-size: 1.2em; margin-bottom: 8px; }
11
+ p { color: #666; font-size: 0.9em; }
12
+ </style>
13
+ </head>
14
+ <body>
15
+ <div class="card">
16
+ <div class="check">&#10003;</div>
17
+ <h1>${t} complete</h1>
18
+ <p>You can close this tab and return to your app.</p>
19
+ </div>
20
+ </body>
21
+ </html>`}function i(e){return `<!DOCTYPE html>
22
+ <html>
23
+ <head>
24
+ <meta charset="utf-8">
25
+ <title>Error</title>
26
+ <style>
27
+ body { font-family: system-ui, sans-serif; display: flex; justify-content: center; align-items: center; min-height: 100vh; margin: 0; color: #1a1a1a; }
28
+ .card { text-align: center; padding: 40px; max-width: 420px; }
29
+ .icon { font-size: 3em; margin-bottom: 12px; }
30
+ h1 { font-size: 1.2em; margin-bottom: 8px; }
31
+ p { color: #dc2626; font-size: 0.9em; word-break: break-word; }
32
+ </style>
33
+ </head>
34
+ <body>
35
+ <div class="card">
36
+ <div class="icon">&#10007;</div>
37
+ <h1>Something went wrong</h1>
38
+ <p>${c(e)}</p>
39
+ </div>
40
+ </body>
41
+ </html>`}function l(e){let t=c(e.recipient),s=c(e.amount),a=c(e.token),n=c(e.network),r=c(e.state),o=c(e.callbackUrl);return `<!DOCTYPE html>
42
+ <html>
43
+ <head>
44
+ <meta charset="utf-8">
45
+ <meta name="viewport" content="width=device-width, initial-scale=1">
46
+ <title>Payment &mdash; ${s} ${a}</title>
47
+ <style>
48
+ * { margin: 0; padding: 0; box-sizing: border-box; }
49
+ body { font-family: system-ui, sans-serif; max-width: 420px; margin: 60px auto; padding: 20px; color: #1a1a1a; }
50
+ h1 { font-size: 1.4em; margin-bottom: 8px; }
51
+ .info { background: #f5f5f5; padding: 16px; border-radius: 8px; margin: 16px 0; font-size: 0.9em; }
52
+ .info dt { color: #666; font-size: 0.85em; margin-top: 8px; }
53
+ .info dd { font-family: monospace; word-break: break-all; }
54
+ button { width: 100%; padding: 14px; font-size: 1em; border: none; border-radius: 8px; cursor: pointer; margin-top: 12px; }
55
+ .btn-primary { background: #2563eb; color: white; }
56
+ .btn-primary:hover { background: #1d4ed8; }
57
+ .btn-primary:disabled { background: #93c5fd; cursor: not-allowed; }
58
+ .status { text-align: center; margin-top: 16px; font-size: 0.9em; color: #666; }
59
+ .success { color: #16a34a; }
60
+ .error { color: #dc2626; }
61
+ </style>
62
+ </head>
63
+ <body>
64
+ <h1>Send ${s} ${a}</h1>
65
+ <dl class="info">
66
+ <dt>To</dt>
67
+ <dd>${t}</dd>
68
+ <dt>Network</dt>
69
+ <dd>${n}</dd>
70
+ <dt>Amount</dt>
71
+ <dd>${s} ${a}</dd>
72
+ </dl>
73
+
74
+ <div id="data"
75
+ data-recipient="${t}"
76
+ data-amount="${s}"
77
+ data-token="${a}"
78
+ data-state="${r}"
79
+ data-callback="${o}"
80
+ ></div>
81
+
82
+ <button class="btn-primary" id="connectBtn">Connect Wallet</button>
83
+ <button class="btn-primary" id="payBtn" style="display:none">Send ${s} ${a}</button>
84
+ <p class="status" id="status"></p>
85
+
86
+ <script src="https://cdnjs.cloudflare.com/ajax/libs/ethers/6.13.4/ethers.umd.min.js"></script>
87
+ <script>
88
+ (function() {
89
+ var d = document.getElementById("data").dataset;
90
+ var RECIPIENT = d.recipient;
91
+ var AMOUNT = d.amount;
92
+ var TOKEN = d.token;
93
+ var STATE = d.state;
94
+ var CALLBACK = d.callback;
95
+ var provider, signer;
96
+ var statusEl = document.getElementById("status");
97
+ var connectBtn = document.getElementById("connectBtn");
98
+ var payBtn = document.getElementById("payBtn");
99
+
100
+ connectBtn.addEventListener("click", async function() {
101
+ try {
102
+ if (!window.ethereum) {
103
+ statusEl.textContent = "No wallet detected. Install MetaMask.";
104
+ statusEl.className = "status error";
105
+ return;
106
+ }
107
+ provider = new ethers.BrowserProvider(window.ethereum);
108
+ signer = await provider.getSigner();
109
+ var addr = await signer.getAddress();
110
+ statusEl.textContent = "Connected: " + addr.slice(0, 6) + "..." + addr.slice(-4);
111
+ statusEl.className = "status";
112
+ connectBtn.style.display = "none";
113
+ payBtn.style.display = "block";
114
+ } catch (e) {
115
+ statusEl.textContent = "Connection failed: " + e.message;
116
+ statusEl.className = "status error";
117
+ }
118
+ });
119
+
120
+ payBtn.addEventListener("click", async function() {
121
+ payBtn.disabled = true;
122
+ statusEl.textContent = "Sending...";
123
+ statusEl.className = "status";
124
+
125
+ try {
126
+ if (TOKEN !== "ETH") {
127
+ statusEl.textContent = "ERC-20 transfers require a contract address. Use ETH for native transfers.";
128
+ statusEl.className = "status error";
129
+ payBtn.disabled = false;
130
+ return;
131
+ }
132
+
133
+ var tx = await signer.sendTransaction({
134
+ to: RECIPIENT,
135
+ value: ethers.parseEther(AMOUNT),
136
+ });
137
+
138
+ statusEl.textContent = "Waiting for confirmation...";
139
+ var receipt = await tx.wait();
140
+
141
+ var res = await fetch(CALLBACK, {
142
+ method: "POST",
143
+ headers: { "Content-Type": "application/json" },
144
+ body: JSON.stringify({
145
+ txHash: receipt.hash,
146
+ state: STATE,
147
+ recipient: RECIPIENT,
148
+ amount: AMOUNT,
149
+ }),
150
+ });
151
+ var data = await res.json();
152
+
153
+ if (data.success) {
154
+ statusEl.textContent = "Payment confirmed! You can close this tab.";
155
+ statusEl.className = "status success";
156
+ } else {
157
+ statusEl.textContent = "Verification failed: " + (data.error || "unknown");
158
+ statusEl.className = "status error";
159
+ payBtn.disabled = false;
160
+ }
161
+ } catch (e) {
162
+ statusEl.textContent = "Transaction failed: " + e.message;
163
+ statusEl.className = "status error";
164
+ payBtn.disabled = false;
165
+ }
166
+ });
167
+ })();
168
+ </script>
169
+ </body>
170
+ </html>`}async function g(e,t,s,a){if(s===true)return {status:500,html:i("GitHub pages require { clientId, clientSecret } configuration")};if(!t.code||!t.state)return {status:400,html:i("Missing code or state parameter")};try{let{handleCallback:n}=await import('./middleware/github.mjs'),r={clientId:s.clientId,clientSecret:s.clientSecret};s.sessionKey&&(r.sessionKey=s.sessionKey);let o=await n(e,{code:t.code,state:t.state},r);return o.success?{status:302,redirect:`${a}/auth/success`}:{status:500,html:i(o.error??"Authentication failed")}}catch(n){return {status:500,html:i(n instanceof Error?n.message:String(n))}}}async function m(e,t,s,a,n){if(s===true)return {status:500,html:i("Google pages require { clientId, clientSecret } configuration")};if(!t.code||!t.state)return {status:400,html:i("Missing code or state parameter")};try{let{handleCallback:r}=await import('./middleware/google.mjs'),o={clientId:s.clientId,clientSecret:s.clientSecret,redirectUri:n};s.sessionKey&&(o.sessionKey=s.sessionKey);let d=await r(e,{code:t.code,state:t.state},o);return d.success?{status:302,redirect:`${a}/auth/success`}:{status:500,html:i(d.error??"Authentication failed")}}catch(r){return {status:500,html:i(r instanceof Error?r.message:String(r))}}}async function p(e,t,s,a){if(s===true)return {status:500,html:i("Stripe pages require { secretKey } configuration")};if(t.cancelled==="true")return {status:200,html:i("Payment was cancelled")};if(!t.session_id||!t.state)return {status:400,html:i("Missing session_id or state parameter")};try{let{handleCallback:n}=await import('./middleware/stripe.mjs'),r={secretKey:s.secretKey};s.sessionKey&&(r.sessionKey=s.sessionKey);let o=await n(e,{checkoutSessionId:t.session_id,state:t.state},r);return o.success?{status:302,redirect:`${a}/payment/success`}:{status:500,html:i(o.error??"Payment verification failed")}}catch(n){return {status:500,html:i(n instanceof Error?n.message:String(n))}}}function f(e,t){return !e.recipient||!e.amount||!e.state?{status:400,html:i("Missing required payment parameters")}:{status:200,html:l({recipient:e.recipient,amount:e.amount,token:e.token??"USDC",network:e.network??"base",state:e.state,callbackUrl:t})}}async function h(e,t,s){if(!t.txHash||!t.state||!t.recipient||!t.amount)return {status:400,json:{success:false,error:"Missing txHash, state, recipient, or amount"}};try{let{handleCallback:a}=await import('./middleware/crypto.mjs'),n={recipient:t.recipient,amount:Number(t.amount)};s!==!0&&(s.rpcUrl&&(n.rpcUrl=s.rpcUrl),s.sessionKey&&(n.sessionKey=s.sessionKey));let r=await a(e,{txHash:t.txHash,state:t.state},n);return {status:r.success?200:500,json:r}}catch(a){return {status:500,json:{success:false,error:a instanceof Error?a.message:String(a)}}}}export{c as a,u as b,i as c,l as d,g as e,m as f,p as g,f as h,h as i};
@@ -0,0 +1 @@
1
+ import {c}from'./chunk-VAAZWX4U.mjs';function d(e){let o=e.name??"url-action",s=e.sessionKey??"user",l=e.timeout??3e5,a=e.declineMessage??"Action cancelled.";return {name:o,onRegister(){return false},async onCall(t,i){if(e.skipIf){if(await Promise.resolve(e.skipIf(t)))return i()}else if(e.persistent){if(await t.userStore.get(s))return i()}else if(t.session.get(s))return i();let n=crypto.randomUUID(),u=await e.buildUrl({sessionId:t.sessionId,elicitationId:n});if((await t.elicit.url(e.message,u,{elicitationId:n,waitForCompletion:true,timeout:l})).action!=="accept")return c(a);if(e.persistent){if(!await t.userStore.get(s))return c("Action was not completed.")}else if(!t.session.get(s))return c("Action was not completed.");return e.onComplete&&await Promise.resolve(e.onComplete(t)),t.session.authorize(o),i()}}}export{d as a};
@@ -0,0 +1 @@
1
+ function u(){let t=new Map;return {async get(e){let n=t.get(e);if(n){if(n.expiresAt!==void 0&&Date.now()>n.expiresAt){t.delete(e);return}return n.value}},async set(e,n,r){t.set(e,{value:n,expiresAt:r!==void 0?Date.now()+r*1e3:void 0});},async delete(e){t.delete(e);}}}function o(t){let e=t.get("user");if(e){if(typeof e=="string")return e;if(typeof e=="object"&&e!==null){let n=e;if(typeof n.id=="string")return n.id;if(typeof n.id=="number")return String(n.id);if(typeof n.sub=="string")return n.sub}}}function d(t,e){let n=()=>{let r=o(t);if(!r)throw new Error("userStore requires a user in session. Call session.set('user', ...) first.");return r};return {async get(r){return e.get(`user:${n()}:${r}`)},async set(r,s,i){await e.set(`user:${n()}:${r}`,s,i);},async delete(r){await e.delete(`user:${n()}:${r}`);}}}export{u as a,o as b,d as c};
package/dist/index.d.ts CHANGED
@@ -1,11 +1,9 @@
1
- import { M as MCPServer } from './types-CqT2idkd.js';
2
- export { E as Elicit, a as ElicitFormResult, b as ElicitUrlOptions, c as ElicitUrlResult, H as HttpAdapterOptions, R as ResourceConfig, d as ResourceContent, e as ResourceContext, f as ResourceHandler, g as RootInfo, S as Sample, h as SampleOptions, i as SampleRawParams, j as SampleRawResult, k as ServerInfo, l as Session, T as TaskConfig, m as TaskContext, n as TaskControl, o as TaskHandler, p as ToolConfig, q as ToolContext, r as ToolHandler, s as ToolInfo, t as ToolMiddleware, u as ToolResponse, v as error, w as image, x as json, y as text } from './types-CqT2idkd.js';
1
+ import { S as ServerOptions, M as MCPServer } from './types-BdFjg9Tn.js';
2
+ export { E as Elicit, a as ElicitFormResult, b as ElicitUrlOptions, c as ElicitUrlResult, H as HttpAdapterOptions, R as ResourceConfig, d as ResourceContent, e as ResourceContext, f as ResourceHandler, g as RootInfo, h as Sample, i as SampleOptions, j as SampleRawParams, k as SampleRawResult, l as ServerInfo, m as Session, n as Store, T as TaskConfig, o as TaskContext, p as TaskControl, q as TaskHandler, r as ToolConfig, s as ToolContext, t as ToolHandler, u as ToolInfo, v as ToolMiddleware, w as ToolResponse, U as UserStore, x as error, y as image, z as json, A as text } from './types-BdFjg9Tn.js';
3
+ export { memoryStore } from './store.js';
3
4
  import '@modelcontextprotocol/sdk/types.js';
4
5
  import 'zod';
5
6
 
6
- declare function createMCPServer(info: {
7
- name: string;
8
- version: string;
9
- }): MCPServer;
7
+ declare function createMCPServer(info: ServerOptions): MCPServer;
10
8
 
11
- export { MCPServer, createMCPServer };
9
+ export { MCPServer, ServerOptions, createMCPServer };
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import {c,d,b,a}from'./chunk-VAAZWX4U.mjs';export{c as error,d as image,b as json,a as text}from'./chunk-VAAZWX4U.mjs';import {InMemoryTaskStore}from'@modelcontextprotocol/sdk/experimental/tasks';import {Server}from'@modelcontextprotocol/sdk/server/index.js';import {ListToolsRequestSchema,CallToolRequestSchema,ListResourcesRequestSchema,ListResourceTemplatesRequestSchema,ReadResourceRequestSchema}from'@modelcontextprotocol/sdk/types.js';import {normalizeObjectSchema}from'@modelcontextprotocol/sdk/server/zod-compat.js';import {toJsonSchemaCompat}from'@modelcontextprotocol/sdk/server/zod-json-schema-compat.js';function j(a){if(a==null)return {type:"object"};let l=normalizeObjectSchema(a);return l?toJsonSchemaCompat(l):a}function $(a,l){let c=l[l.length-1];if(typeof c!="function")throw new TypeError(`${a}: last argument must be a handler function`);let i=l[l.length-2];if(i==null||typeof i!="object"||Array.isArray(i))throw new TypeError(`${a}: second-to-last argument must be a config object`);let d=l.slice(0,-2);for(let u of d)if(!u||typeof u!="object"||typeof u.name!="string")throw new TypeError(`${a}: each middleware must have a "name" property`);return {middlewares:d,config:i,handler:c}}function A(a,l){let c=[];for(let i of l)i.onRegister?.(a)===false&&c.push(i.name);return c}function Q(a){let c=a.split(/\{[^}]+\}/).map(i=>i.replace(/[.*+?^$|()[\]\\]/g,"\\$&"));return new RegExp(`^${c.join("(.+)")}$`)}function B(a,l,c,i){let d=c.get(l);if(d==="disabled")return false;if(d==="enabled")return true;for(let u of a)if(!i.has(u))return false;return true}function X(a,l){let c=a.get(l);if(c)return c;for(let i of a.values())if(i.isTemplate&&i.uriPattern?.test(l))return i}function U(a,l,c){let i=a.filter(m=>m.onCall),d=a.filter(m=>m.onResult).reverse(),u=0,p=async()=>{if(u>=i.length){let S=await c();for(let C of d)S=await C.onResult(S,l);return S}return i[u++].onCall(l,p)};return p}function pe(a,l,c){return {async form(i,d){let u=j(d),p=await a.elicitInput({message:i,requestedSchema:u});return {action:p.action,content:p.content??{}}},async url(i,d,u){let p=u?.elicitationId??crypto.randomUUID(),m;u?.waitForCompletion&&l&&(m=l(p,a));let S=await a.elicitInput({mode:"url",message:i,url:d,elicitationId:p});if(S.action==="accept"&&m){let C=u?.timeout??3e5,x=new Promise((G,I)=>{setTimeout(()=>I(new Error("Elicitation timed out")),C);});await Promise.race([m,x]);}else m&&c&&c(p);return {action:S.action}}}}function F(a){return async()=>{try{return (await a.listRoots()).roots.map(c=>{let i={uri:c.uri};return c.name!==void 0&&(i.name=c.name),i})}catch{return []}}}function fe(a){async function l(i,d){let u={messages:[{role:"user",content:{type:"text",text:i}}],maxTokens:d?.maxTokens??1024};d?.model!==void 0&&(u.modelPreferences={hints:[{name:d.model}]}),d?.system!==void 0&&(u.systemPrompt=d.system),d?.temperature!==void 0&&(u.temperature=d.temperature),d?.stopSequences!==void 0&&(u.stopSequences=d.stopSequences);let m=(await a.createMessage(u)).content;return m.type==="text"?m.text:""}async function c(i){return a.createMessage(i)}return Object.assign(l,{raw:c})}function N(a$1,l,c$1,i,d$1,u,p){return {toolName:i,session:c$1,signal:d$1,sessionId:l,elicit:pe(a$1,u,p),roots:F(a$1),sample:fe(a$1),text:a,json:b,error:c,image:d}}function ve(a){let l=[],c$1=new Map,i=new Map,d=new Map,u=new Map,p=new Map,m=new Map,S=36e5;function C(){let e=Date.now();for(let[t,n]of m)e-n.createdAt>S&&m.delete(t);}function x(e,t,n){return C(),new Promise(o=>{let r;try{r=n.createElicitationCompletionNotifier(e);}catch{}m.set(e,{resolver:o,completionNotifier:r,createdAt:Date.now()});})}function G(e){C();let t=m.get(e);t&&(m.delete(e),t.completionNotifier&&t.completionNotifier().catch(()=>{}),t.resolver());}function I(e){let t=m.get(e);t&&(m.delete(e),t.resolver());}let q=new Set,ee=new InMemoryTaskStore,W=new Proxy(ee,{get(e,t,n){return t==="updateTaskStatus"?async(o,r,...s)=>(r==="cancelled"&&q.add(o),e.updateTaskStatus.call(e,o,r,...s)):Reflect.get(e,t,n)}}),k=new Server(a,{capabilities:{tools:{listChanged:true},resources:{listChanged:true},tasks:{list:{},cancel:{},requests:{tools:{call:{}}}}},taskStore:W});function E(e){let t=u.get(e);return t||(t={data:new Map,grants:new Set,toolOverrides:new Map,resourceOverrides:new Map},u.set(e,t)),t}function V(e,t){let n=E(t);return B(e.hiddenByMiddlewares,e.name,n.toolOverrides,n.grants)}function H(e,t){let n=E(t);return B(e.hiddenByMiddlewares,e.uri,n.resourceOverrides,n.grants)}function J(e,t){let n=E(t);return B(e.hiddenByMiddlewares,e.name,n.toolOverrides,n.grants)}function O(e){(e&&p.get(e)||k).sendToolListChanged().catch(()=>{});}function _(e){(e&&p.get(e)||k).sendResourceListChanged().catch(()=>{});}function b(e){let t=E(e);return {get(n){return t.data.get(n)},set(n,o){t.data.set(n,o);},authorize(n){t.grants.add(n),O(e),_(e);},revoke(n){t.grants.delete(n),O(e),_(e);},enableTools(...n){for(let o of n)t.toolOverrides.set(o,"enabled");O(e);},disableTools(...n){for(let o of n)t.toolOverrides.set(o,"disabled");O(e);},enableResources(...n){for(let o of n)t.resourceOverrides.set(o,"enabled");_(e);},disableResources(...n){for(let o of n)t.resourceOverrides.set(o,"disabled");_(e);}}}function Z(e){e.setRequestHandler(ListToolsRequestSchema,(t,n)=>{let o=n.sessionId??"default",r=[];for(let s of c$1.values())V(s,o)&&r.push({name:s.name,description:s.description,inputSchema:j(s.input)});for(let s of d.values())J(s,o)&&r.push({name:s.name,description:s.description,inputSchema:j(s.input),execution:{taskSupport:"required"}});return {tools:r}}),e.setRequestHandler(CallToolRequestSchema,async(t,n)=>{let{name:o,arguments:r}=t.params,s=n.sessionId??"default",g=c$1.get(o);if(g){if(!V(g,s))return c(`Tool not available: ${o}`);let w=N(e,s,b(s),o,n.signal,(R,M)=>x(R,s,M),I),f=()=>Promise.resolve(g.handler(r??{},w));return U(g.middlewares,w,f)()}let T=d.get(o);if(T){if(!J(T,s))return c(`Tool not available: ${o}`);let w=n.taskStore;if(!w)return c("Task store not available");let f=await w.createTask({pollInterval:1e3}),h=f.taskId,R={progress(y,P){if(q.has(h))return;let de=P?`${y}% ${P}`:`${y}%`;w.updateTaskStatus(h,"working",de).catch(()=>{});},get cancelled(){return q.has(h)}},M={...N(e,s,b(s),o,n.signal,(y,P)=>x(y,s,P),I),task:R},ce=async()=>((async()=>{try{let y=await T.handler(r??{},M);q.has(h)||await w.storeTaskResult(h,"completed",y);}catch(y){if(!q.has(h)){let P=y instanceof Error?y.message:String(y);await w.storeTaskResult(h,"failed",c(P)).catch(()=>{});}}})(),{task:f});return U(T.middlewares,M,ce)()}return c(`Unknown tool: ${o}`)}),e.setRequestHandler(ListResourcesRequestSchema,(t,n)=>{let o=n.sessionId??"default",r=[];for(let s of i.values())!s.isTemplate&&H(s,o)&&r.push({uri:s.uri,name:s.name,description:s.description,mimeType:s.mimeType});return {resources:r}}),e.setRequestHandler(ListResourceTemplatesRequestSchema,(t,n)=>{let o=n.sessionId??"default",r=[];for(let s of i.values())s.isTemplate&&H(s,o)&&r.push({uriTemplate:s.uri,name:s.name,description:s.description,mimeType:s.mimeType});return {resourceTemplates:r}}),e.setRequestHandler(ReadResourceRequestSchema,async(t,n)=>{let{uri:o}=t.params,r=X(i,o);if(!r)throw new Error(`Unknown resource: ${o}`);let s=n.sessionId??"default";if(!H(r,s))throw new Error(`Resource not available: ${o}`);let g=b(s),T={uri:o,session:g,sessionId:s,roots:F(e)},w=N(e,s,g,r.uri,n.signal,(R,M)=>x(R,s,M),I),f=async()=>{let R=await r.handler(o,T);return {contents:[{uri:o,mimeType:R.mimeType??r.mimeType,...R.text!=null?{text:R.text}:{},...R.blob!=null?{blob:R.blob}:{}}]}};return U(r.middlewares,w,f)()});}Z(k);function te(e){l.push(e);}function ne(...e){let t=e[0],n=$(`tool("${t}")`,e.slice(1));if(typeof n.config.name=="string")throw new TypeError(`tool("${t}"): second-to-last argument must be a config object`);let o=n.config,r=[...l,...n.middlewares],s={name:t,description:o.description,middlewares:r};c$1.set(t,{name:t,description:o.description,input:o.input,handler:n.handler,middlewares:r,hiddenByMiddlewares:A(s,r)});}function oe(...e){let t=e[0],n=$(`resource("${t}")`,e.slice(1));if(typeof n.config.name!="string")throw new TypeError(`resource("${t}"): second-to-last argument must be a config object with a "name" property`);let o=n.config,r={name:o.name,description:o.description,middlewares:n.middlewares},s=t.includes("{");i.set(t,{uri:t,isTemplate:s,uriPattern:s?Q(t):null,name:o.name,description:o.description,mimeType:o.mimeType,handler:n.handler,middlewares:n.middlewares,hiddenByMiddlewares:A(r,n.middlewares)});}function se(...e){let t=e[0],n=$(`task("${t}")`,e.slice(1));if(typeof n.config.name=="string")throw new TypeError(`task("${t}"): second-to-last argument must be a config object`);let o=n.config,r=[...l,...n.middlewares],s={name:t,description:o.description,middlewares:r};d.set(t,{name:t,description:o.description,input:o.input,handler:n.handler,middlewares:r,hiddenByMiddlewares:A(s,r)});}async function re(){let{StdioServerTransport:e}=await import('@modelcontextprotocol/sdk/server/stdio.js'),t=new e;await k.connect(t);}async function ie(e){await k.connect(e);}let ae={tools:{listChanged:true},resources:{listChanged:true},tasks:{list:{},cancel:{},requests:{tools:{call:{}}}}};function K(){let e=new Server(a,{capabilities:ae,taskStore:W});return Z(e),e}function le(e){let t=null;async function n(){return t||(t=(await import('@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js')).WebStandardStreamableHTTPServerTransport),t}if(e?.sessionless)return async r=>{let s=await n(),g=K(),T=new s({sessionIdGenerator:void 0,enableJsonResponse:e?.enableJsonResponse});return await g.connect(T),T.handleRequest(r)};let o=new Map;return async r=>{let s=await n(),g=r.headers.get("mcp-session-id");if(g){let f=o.get(g);return f?(e?.onRequest&&await e.onRequest(r,g,b(g)),f.transport.handleRequest(r)):new Response(JSON.stringify({jsonrpc:"2.0",error:{code:-32e3,message:"Session not found"}}),{status:404,headers:{"Content-Type":"application/json"}})}let T=K(),w=new s({sessionIdGenerator:e?.sessionIdGenerator??(()=>crypto.randomUUID()),enableJsonResponse:e?.enableJsonResponse,onsessioninitialized:f=>{o.set(f,{server:T,transport:w}),p.set(f,T),e?.onRequest&&e.onRequest(r,f,b(f));},onsessionclosed:f=>{o.delete(f),p.delete(f);}});return await T.connect(w),w.handleRequest(r)}}return {use:te,tool:ne,resource:oe,task:se,stdio:re,http:le,session:b,completeElicitation:G,connect:ie,_server:k,_getSession:E,_isToolVisible(e,t){let n=c$1.get(e);return n?V(n,t):false},_isResourceVisible(e,t){let n=i.get(e);return n?H(n,t):false},_isTaskVisible(e,t){let n=d.get(e);return n?J(n,t):false},_createSessionAPI:b}}export{ve as createMCPServer};
1
+ import {a,c as c$1}from'./chunk-SPZY5GJA.mjs';export{a as memoryStore}from'./chunk-SPZY5GJA.mjs';import {c,d,b,a as a$1}from'./chunk-VAAZWX4U.mjs';export{c as error,d as image,b as json,a as text}from'./chunk-VAAZWX4U.mjs';import {InMemoryTaskStore}from'@modelcontextprotocol/sdk/experimental/tasks';import {Server}from'@modelcontextprotocol/sdk/server/index.js';import {ListToolsRequestSchema,CallToolRequestSchema,ListResourcesRequestSchema,ListResourceTemplatesRequestSchema,ReadResourceRequestSchema}from'@modelcontextprotocol/sdk/types.js';import {normalizeObjectSchema}from'@modelcontextprotocol/sdk/server/zod-compat.js';import {toJsonSchemaCompat}from'@modelcontextprotocol/sdk/server/zod-json-schema-compat.js';function q(i){if(i==null)return {type:"object"};let l=normalizeObjectSchema(i);return l?toJsonSchemaCompat(l):i}function A(i,l){let c=l[l.length-1];if(typeof c!="function")throw new TypeError(`${i}: last argument must be a handler function`);let a=l[l.length-2];if(a==null||typeof a!="object"||Array.isArray(a))throw new TypeError(`${i}: second-to-last argument must be a config object`);let d=l.slice(0,-2);for(let u of d)if(!u||typeof u!="object"||typeof u.name!="string")throw new TypeError(`${i}: each middleware must have a "name" property`);return {middlewares:d,config:a,handler:c}}function U(i,l){let c=[];for(let a of l)a.onRegister?.(i)===false&&c.push(a.name);return c}function ee(i){let c=i.split(/\{[^}]+\}/).map(a=>a.replace(/[.*+?^$|()[\]\\]/g,"\\$&"));return new RegExp(`^${c.join("(.+)")}$`)}function B(i,l,c,a){let d=c.get(l);if(d==="disabled")return false;if(d==="enabled")return true;for(let u of i)if(!a.has(u))return false;return true}function te(i,l){let c=i.get(l);if(c)return c;for(let a of i.values())if(a.isTemplate&&a.uriPattern?.test(l))return a}function N(i,l,c){let a=i.filter(m=>m.onCall),d=i.filter(m=>m.onResult).reverse(),u=0,f=async()=>{if(u>=a.length){let w=await c();for(let P of d)w=await P.onResult(w,l);return w}return a[u++].onCall(l,f)};return f}function we(i,l,c){return {async form(a,d){let u=q(d),f=await i.elicitInput({message:a,requestedSchema:u});return {action:f.action,content:f.content??{}}},async url(a,d,u){let f=u?.elicitationId??crypto.randomUUID(),m;u?.waitForCompletion&&l&&(m=l(f,i));let w=await i.elicitInput({mode:"url",message:a,url:d,elicitationId:f});if(w.action==="accept"&&m){let P=u?.timeout??3e5,E=new Promise((j,J)=>{setTimeout(()=>J(new Error("Elicitation timed out")),P);});await Promise.race([m,E]);}else m&&c&&c(f);return {action:w.action}}}}function K(i){return async()=>{try{return (await i.listRoots()).roots.map(c=>{let a={uri:c.uri};return c.name!==void 0&&(a.name=c.name),a})}catch{return []}}}function Te(i){async function l(a,d){let u={messages:[{role:"user",content:{type:"text",text:a}}],maxTokens:d?.maxTokens??1024};d?.model!==void 0&&(u.modelPreferences={hints:[{name:d.model}]}),d?.system!==void 0&&(u.systemPrompt=d.system),d?.temperature!==void 0&&(u.temperature=d.temperature),d?.stopSequences!==void 0&&(u.stopSequences=d.stopSequences);let m=(await i.createMessage(u)).content;return m.type==="text"?m.text:""}async function c(a){return i.createMessage(a)}return Object.assign(l,{raw:c})}function V(i,l,c$2,a,d$1,u,f,m){return {toolName:a,session:c$2,signal:d$1,sessionId:l,elicit:we(i,f,m),roots:K(i),sample:Te(i),text:a$1,json:b,error:c,image:d,store:u,userStore:c$1(c$2,u)}}function Ce(i){let l=i.store??a(),c$2=[],a$1=new Map,d=new Map,u=new Map,f=new Map,m=new Map,w=new Map,P=36e5;function E(){let e=Date.now();for(let[t,n]of w)e-n.createdAt>P&&w.delete(t);}function j(e,t,n){return E(),new Promise(o=>{let r;try{r=n.createElicitationCompletionNotifier(e);}catch{}w.set(e,{resolver:o,completionNotifier:r,createdAt:Date.now()});})}function J(e){E();let t=w.get(e);t&&(w.delete(e),t.completionNotifier&&t.completionNotifier().catch(()=>{}),t.resolver());}function L(e){let t=w.get(e);t&&(w.delete(e),t.resolver());}let x=new Set,oe=new InMemoryTaskStore,Q=new Proxy(oe,{get(e,t,n){return t==="updateTaskStatus"?async(o,r,...s)=>(r==="cancelled"&&x.add(o),e.updateTaskStatus.call(e,o,r,...s)):Reflect.get(e,t,n)}}),C=new Server(i,{capabilities:{tools:{listChanged:true},resources:{listChanged:true},tasks:{list:{},cancel:{},requests:{tools:{call:{}}}}},taskStore:Q});function I(e){let t=f.get(e);return t||(t={data:new Map,grants:new Set,toolOverrides:new Map,resourceOverrides:new Map},f.set(e,t)),t}function z(e,t){let n=I(t);return B(e.hiddenByMiddlewares,e.name,n.toolOverrides,n.grants)}function H(e,t){let n=I(t);return B(e.hiddenByMiddlewares,e.uri,n.resourceOverrides,n.grants)}function D(e,t){let n=I(t);return B(e.hiddenByMiddlewares,e.name,n.toolOverrides,n.grants)}function O(e){(e&&m.get(e)||C).sendToolListChanged().catch(()=>{});}function _(e){(e&&m.get(e)||C).sendResourceListChanged().catch(()=>{});}function b(e){let t=I(e);return {get(n){return t.data.get(n)},set(n,o){t.data.set(n,o);},authorize(n){t.grants.add(n),O(e),_(e);},revoke(n){t.grants.delete(n),O(e),_(e);},enableTools(...n){for(let o of n)t.toolOverrides.set(o,"enabled");O(e);},disableTools(...n){for(let o of n)t.toolOverrides.set(o,"disabled");O(e);},enableResources(...n){for(let o of n)t.resourceOverrides.set(o,"enabled");_(e);},disableResources(...n){for(let o of n)t.resourceOverrides.set(o,"disabled");_(e);}}}function X(e){e.setRequestHandler(ListToolsRequestSchema,(t,n)=>{let o=n.sessionId??"default",r=[];for(let s of a$1.values())z(s,o)&&r.push({name:s.name,description:s.description,inputSchema:q(s.input)});for(let s of u.values())D(s,o)&&r.push({name:s.name,description:s.description,inputSchema:q(s.input),execution:{taskSupport:"required"}});return {tools:r}}),e.setRequestHandler(CallToolRequestSchema,async(t,n)=>{let{name:o,arguments:r}=t.params,s=n.sessionId??"default",g=a$1.get(o);if(g){if(!z(g,s))return c(`Tool not available: ${o}`);let T=V(e,s,b(s),o,n.signal,l,(y,k)=>j(y,s,k),L),p=()=>Promise.resolve(g.handler(r??{},T));return N(g.middlewares,T,p)()}let R=u.get(o);if(R){if(!D(R,s))return c(`Tool not available: ${o}`);let T=n.taskStore;if(!T)return c("Task store not available");let p=await T.createTask({pollInterval:1e3}),h=p.taskId,y={progress(S,M){if(x.has(h))return;let pe=M?`${S}% ${M}`:`${S}%`;T.updateTaskStatus(h,"working",pe).catch(()=>{});},get cancelled(){return x.has(h)}},k={...V(e,s,b(s),o,n.signal,l,(S,M)=>j(S,s,M),L),task:y},me=async()=>((async()=>{try{let S=await R.handler(r??{},k);x.has(h)||await T.storeTaskResult(h,"completed",S);}catch(S){if(!x.has(h)){let M=S instanceof Error?S.message:String(S);await T.storeTaskResult(h,"failed",c(M)).catch(()=>{});}}})(),{task:p});return N(R.middlewares,k,me)()}return c(`Unknown tool: ${o}`)}),e.setRequestHandler(ListResourcesRequestSchema,(t,n)=>{let o=n.sessionId??"default",r=[];for(let s of d.values())!s.isTemplate&&H(s,o)&&r.push({uri:s.uri,name:s.name,description:s.description,mimeType:s.mimeType});return {resources:r}}),e.setRequestHandler(ListResourceTemplatesRequestSchema,(t,n)=>{let o=n.sessionId??"default",r=[];for(let s of d.values())s.isTemplate&&H(s,o)&&r.push({uriTemplate:s.uri,name:s.name,description:s.description,mimeType:s.mimeType});return {resourceTemplates:r}}),e.setRequestHandler(ReadResourceRequestSchema,async(t,n)=>{let{uri:o}=t.params,r=te(d,o);if(!r)throw new Error(`Unknown resource: ${o}`);let s=n.sessionId??"default";if(!H(r,s))throw new Error(`Resource not available: ${o}`);let g=b(s),R={uri:o,session:g,sessionId:s,roots:K(e),store:l,userStore:c$1(g,l)},T=V(e,s,g,r.uri,n.signal,l,(y,k)=>j(y,s,k),L),p=async()=>{let y=await r.handler(o,R);return {contents:[{uri:o,mimeType:y.mimeType??r.mimeType,...y.text!=null?{text:y.text}:{},...y.blob!=null?{blob:y.blob}:{}}]}};return N(r.middlewares,T,p)()});}X(C);function se(e){c$2.push(e);}function re(...e){let t=e[0],n=A(`tool("${t}")`,e.slice(1));if(typeof n.config.name=="string")throw new TypeError(`tool("${t}"): second-to-last argument must be a config object`);let o=n.config,r=[...c$2,...n.middlewares],s={name:t,description:o.description,middlewares:r};a$1.set(t,{name:t,description:o.description,input:o.input,handler:n.handler,middlewares:r,hiddenByMiddlewares:U(s,r)});}function ie(...e){let t=e[0],n=A(`resource("${t}")`,e.slice(1));if(typeof n.config.name!="string")throw new TypeError(`resource("${t}"): second-to-last argument must be a config object with a "name" property`);let o=n.config,r={name:o.name,description:o.description,middlewares:n.middlewares},s=t.includes("{");d.set(t,{uri:t,isTemplate:s,uriPattern:s?ee(t):null,name:o.name,description:o.description,mimeType:o.mimeType,handler:n.handler,middlewares:n.middlewares,hiddenByMiddlewares:U(r,n.middlewares)});}function ae(...e){let t=e[0],n=A(`task("${t}")`,e.slice(1));if(typeof n.config.name=="string")throw new TypeError(`task("${t}"): second-to-last argument must be a config object`);let o=n.config,r=[...c$2,...n.middlewares],s={name:t,description:o.description,middlewares:r};u.set(t,{name:t,description:o.description,input:o.input,handler:n.handler,middlewares:r,hiddenByMiddlewares:U(s,r)});}async function le(){let{StdioServerTransport:e}=await import('@modelcontextprotocol/sdk/server/stdio.js'),t=new e;await C.connect(t);}async function ce(e){await C.connect(e);}let de={tools:{listChanged:true},resources:{listChanged:true},tasks:{list:{},cancel:{},requests:{tools:{call:{}}}}};function Y(){let e=new Server(i,{capabilities:de,taskStore:Q});return X(e),e}function ue(e){let t=null;async function n(){return t||(t=(await import('@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js')).WebStandardStreamableHTTPServerTransport),t}if(e?.sessionless)return async r=>{let s=await n(),g=Y(),R=new s({sessionIdGenerator:void 0,enableJsonResponse:e?.enableJsonResponse});return await g.connect(R),R.handleRequest(r)};let o=new Map;return async r=>{let s=await n(),g=r.headers.get("mcp-session-id");if(g){let p=o.get(g);return p?(e?.onRequest&&await e.onRequest(r,g,b(g)),p.transport.handleRequest(r)):new Response(JSON.stringify({jsonrpc:"2.0",error:{code:-32e3,message:"Session not found"}}),{status:404,headers:{"Content-Type":"application/json"}})}let R=Y(),T=new s({sessionIdGenerator:e?.sessionIdGenerator??(()=>crypto.randomUUID()),enableJsonResponse:e?.enableJsonResponse,onsessioninitialized:p=>{o.set(p,{server:R,transport:T}),m.set(p,R),e?.onRequest&&e.onRequest(r,p,b(p));},onsessionclosed:p=>{o.delete(p),m.delete(p);}});return await R.connect(T),T.handleRequest(r)}}return {use:se,tool:re,resource:ie,task:ae,stdio:le,http:ue,session:b,completeElicitation:J,store:l,connect:ce,_server:C,_getSession:I,_isToolVisible(e,t){let n=a$1.get(e);return n?z(n,t):false},_isResourceVisible(e,t){let n=d.get(e);return n?H(n,t):false},_isTaskVisible(e,t){let n=u.get(e);return n?D(n,t):false},_createSessionAPI:b}}export{Ce as createMCPServer};
@@ -1,4 +1,4 @@
1
- import { t as ToolMiddleware } from '../types-CqT2idkd.js';
1
+ import { v as ToolMiddleware } from '../types-BdFjg9Tn.js';
2
2
  import { GuardOptions } from './guard.js';
3
3
  import '@modelcontextprotocol/sdk/types.js';
4
4
  import 'zod';
@@ -1,4 +1,4 @@
1
- import { t as ToolMiddleware } from '../types-CqT2idkd.js';
1
+ import { v as ToolMiddleware } from '../types-BdFjg9Tn.js';
2
2
  import '@modelcontextprotocol/sdk/types.js';
3
3
  import 'zod';
4
4
 
@@ -1,4 +1,4 @@
1
- import { t as ToolMiddleware, q as ToolContext } from '../types-CqT2idkd.js';
1
+ import { v as ToolMiddleware, s as ToolContext } from '../types-BdFjg9Tn.js';
2
2
  import '@modelcontextprotocol/sdk/types.js';
3
3
  import 'zod';
4
4
 
@@ -1,5 +1,5 @@
1
1
  import { z } from 'zod';
2
- import { t as ToolMiddleware } from '../types-CqT2idkd.js';
2
+ import { v as ToolMiddleware } from '../types-BdFjg9Tn.js';
3
3
  import '@modelcontextprotocol/sdk/types.js';
4
4
 
5
5
  interface CredentialsOptions<T extends z.ZodObject<z.ZodRawShape>> {
@@ -0,0 +1,64 @@
1
+ import { s as ToolContext, v as ToolMiddleware, M as MCPServer } from '../types-BdFjg9Tn.js';
2
+ import '@modelcontextprotocol/sdk/types.js';
3
+ import 'zod';
4
+
5
+ interface CryptoPaymentOptions {
6
+ /** Middleware name. Default: "crypto" */
7
+ name?: string;
8
+ /** Token symbol. Default: "USDC" */
9
+ token?: "USDC" | "USDT" | "DAI" | "ETH" | string;
10
+ /** Recipient wallet address. */
11
+ recipient: string;
12
+ /** Amount in token units. */
13
+ amount: number;
14
+ /** Network. Default: "base" */
15
+ network?: "base" | "base-sepolia" | "ethereum" | "polygon" | "solana" | string;
16
+ /** Base URL of your server. */
17
+ baseUrl: string;
18
+ /** Callback path. Default: "/payment/crypto/callback" */
19
+ callbackPath?: string;
20
+ /** Session key for payment data. Default: "payment" */
21
+ sessionKey?: string;
22
+ /** If true, only charge once per session per tool. Default: false */
23
+ once?: boolean;
24
+ /** Message shown to user. */
25
+ message?: string;
26
+ /** Timeout in ms. Default: 300000 */
27
+ timeout?: number;
28
+ /** Custom skip condition. Takes priority over sessionKey check. */
29
+ skipIf?: (c: ToolContext) => boolean | Promise<boolean>;
30
+ /** Called after payment completes successfully, before next(). */
31
+ onComplete?: (c: ToolContext) => void | Promise<void>;
32
+ }
33
+ /** @deprecated Use `CryptoPaymentOptions` instead. */
34
+ type UsdcPaymentOptions = CryptoPaymentOptions;
35
+ declare function crypto(options: CryptoPaymentOptions): ToolMiddleware;
36
+ /** @deprecated Use `crypto()` from `lynq/crypto` instead. */
37
+ declare const usdcPayment: typeof crypto;
38
+ interface HandleCallbackOptions {
39
+ /** RPC URL for the network. */
40
+ rpcUrl?: string;
41
+ /** Expected recipient address. */
42
+ recipient: string;
43
+ /** Expected amount. */
44
+ amount: number;
45
+ /** Session key. Default: "payment" */
46
+ sessionKey?: string;
47
+ }
48
+ /** @deprecated Use `HandleCallbackOptions` instead. */
49
+ type HandleUsdcCallbackOptions = HandleCallbackOptions;
50
+ /**
51
+ * Handle crypto payment callback. Call from your HTTP callback route.
52
+ * Verifies the on-chain transaction, stores in session, and completes elicitation.
53
+ */
54
+ declare function handleCallback(server: MCPServer, params: {
55
+ state: string;
56
+ txHash: string;
57
+ }, options: HandleCallbackOptions): Promise<{
58
+ success: boolean;
59
+ error?: string;
60
+ }>;
61
+ /** @deprecated Use `handleCallback()` from `lynq/crypto` instead. */
62
+ declare const handleUsdcCallback: typeof handleCallback;
63
+
64
+ export { type CryptoPaymentOptions, type HandleCallbackOptions, type HandleUsdcCallbackOptions, type UsdcPaymentOptions, crypto, handleCallback, handleUsdcCallback, usdcPayment };
@@ -0,0 +1,2 @@
1
+ import {a}from'../chunk-BVDKAIOU.mjs';import'../chunk-OYHVJKUP.mjs';import'../chunk-VAAZWX4U.mjs';function g(e){let{recipient:s,amount:t,token:r="USDC",network:a$1="base",baseUrl:o,callbackPath:n="/payment/crypto/callback",once:p=false}=e,y=e.name??"crypto",m=e.sessionKey??"payment",f=e.message??`Payment required (${t} ${r}).`,i={name:y,sessionKey:m,message:f,buildUrl:({sessionId:c,elicitationId:l})=>{let b=new URLSearchParams({recipient:s,amount:String(t),token:r,network:a$1,state:`${c}:${l}`});return `${o}${n}?${b}`}};e.timeout!==void 0&&(i.timeout=e.timeout),e.skipIf&&(i.skipIf=e.skipIf),e.onComplete&&(i.onComplete=e.onComplete);let u=a(i);return p?u:{...u,onResult(c,l){return l.session.set(m,void 0),c}}}var P=g;async function C(e,s,t){let r=t.sessionKey??"payment",[a,o]=s.state.split(":");if(!a||!o)return {success:false,error:"Invalid state parameter"};try{return await h(s.txHash,t)?(e.session(a).set(r,{provider:"crypto",txHash:s.txHash,amount:t.amount,recipient:t.recipient,paidAt:new Date().toISOString()}),e.completeElicitation(o),{success:!0}):{success:!1,error:"Transaction verification failed"}}catch(n){return {success:false,error:n instanceof Error?n.message:String(n)}}}var x=C;async function h(e,s){let t=s.rpcUrl??"https://mainnet.base.org";try{return (await(await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:"eth_getTransactionReceipt",params:[e]})})).json()).result?.status==="0x1"}catch{return false}}
2
+ export{g as crypto,C as handleCallback,x as handleUsdcCallback,P as usdcPayment};
@@ -0,0 +1,54 @@
1
+ import { s as ToolContext, v as ToolMiddleware, M as MCPServer } from '../types-BdFjg9Tn.js';
2
+ import '@modelcontextprotocol/sdk/types.js';
3
+ import 'zod';
4
+
5
+ interface GitHubOptions {
6
+ /** Middleware name. Default: "github" */
7
+ name?: string;
8
+ /** GitHub OAuth App client ID. */
9
+ clientId: string;
10
+ /** GitHub OAuth App client secret. */
11
+ clientSecret: string;
12
+ /** OAuth callback URL (your server's callback endpoint). */
13
+ redirectUri: string;
14
+ /** GitHub OAuth scopes. Default: [] */
15
+ scopes?: string[];
16
+ /** Session key for user data. Default: "user" */
17
+ sessionKey?: string;
18
+ /** Message shown to the user. Default: "Please sign in with GitHub to continue." */
19
+ message?: string;
20
+ /** Timeout in ms. Default: 300000 */
21
+ timeout?: number;
22
+ /** Custom skip condition. Takes priority over sessionKey check. */
23
+ skipIf?: (c: ToolContext) => boolean | Promise<boolean>;
24
+ /** Called after authentication completes successfully, before next(). */
25
+ onComplete?: (c: ToolContext) => void | Promise<void>;
26
+ }
27
+ /** @deprecated Use `GitHubOptions` instead. */
28
+ type GitHubOAuthOptions = GitHubOptions;
29
+ declare function github(options: GitHubOptions): ToolMiddleware;
30
+ /** @deprecated Use `github()` from `lynq/github` instead. */
31
+ declare const githubOAuth: typeof github;
32
+ interface HandleCallbackOptions {
33
+ clientId: string;
34
+ clientSecret: string;
35
+ /** Session key for user data. Default: "user" */
36
+ sessionKey?: string;
37
+ }
38
+ /** @deprecated Use `HandleCallbackOptions` instead. */
39
+ type HandleGitHubCallbackOptions = HandleCallbackOptions;
40
+ /**
41
+ * Handle GitHub OAuth callback. Call from your HTTP callback route.
42
+ * Exchanges code for token, fetches user info, stores in session, and completes elicitation.
43
+ */
44
+ declare function handleCallback(server: MCPServer, params: {
45
+ code: string;
46
+ state: string;
47
+ }, options: HandleCallbackOptions): Promise<{
48
+ success: boolean;
49
+ error?: string;
50
+ }>;
51
+ /** @deprecated Use `handleCallback()` from `lynq/github` instead. */
52
+ declare const handleGitHubCallback: typeof handleCallback;
53
+
54
+ export { type GitHubOAuthOptions, type GitHubOptions, type HandleCallbackOptions, type HandleGitHubCallbackOptions, github, githubOAuth, handleCallback, handleGitHubCallback };
@@ -0,0 +1,2 @@
1
+ import {a}from'../chunk-INAAPNKG.mjs';import'../chunk-OYHVJKUP.mjs';import'../chunk-VAAZWX4U.mjs';function p(e){let s=e.scopes??[],t={name:e.name??"github",sessionKey:e.sessionKey??"user",message:e.message??"Please sign in with GitHub to continue.",buildUrl({sessionId:c,elicitationId:n}){let r=new URLSearchParams({client_id:e.clientId,redirect_uri:e.redirectUri,state:`${c}:${n}`});return s.length>0&&r.set("scope",s.join(" ")),`https://github.com/login/oauth/authorize?${r}`}};return e.timeout!==void 0&&(t.timeout=e.timeout),e.skipIf&&(t.skipIf=e.skipIf),e.onComplete&&(t.onComplete=e.onComplete),a(t)}var h=p;async function d(e,s,t){let c=t.sessionKey??"user",[n,r]=s.state.split(":");if(!n||!r)return {success:false,error:"Invalid state parameter"};try{let i=await(await fetch("https://github.com/login/oauth/access_token",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({client_id:t.clientId,client_secret:t.clientSecret,code:s.code})})).json();if(!i.access_token)return {success:!1,error:i.error_description??i.error??"Token exchange failed"};let u=await(await fetch("https://api.github.com/user",{headers:{Authorization:`Bearer ${i.access_token}`}})).json(),a=e.session(n);return a.set(c,u),a.set("accessToken",i.access_token),e.completeElicitation(r),{success:!0}}catch(o){return {success:false,error:o instanceof Error?o.message:String(o)}}}var f=d;
2
+ export{p as github,h as githubOAuth,d as handleCallback,f as handleGitHubCallback};
@@ -0,0 +1,55 @@
1
+ import { s as ToolContext, v as ToolMiddleware, M as MCPServer } from '../types-BdFjg9Tn.js';
2
+ import '@modelcontextprotocol/sdk/types.js';
3
+ import 'zod';
4
+
5
+ interface GoogleOptions {
6
+ /** Middleware name. Default: "google" */
7
+ name?: string;
8
+ /** Google OAuth client ID. */
9
+ clientId: string;
10
+ /** Google OAuth client secret. */
11
+ clientSecret: string;
12
+ /** OAuth callback URL (your server's callback endpoint). */
13
+ redirectUri: string;
14
+ /** OAuth scopes. Default: ["openid", "profile", "email"] */
15
+ scopes?: string[];
16
+ /** Session key for user data. Default: "user" */
17
+ sessionKey?: string;
18
+ /** Message shown to the user. Default: "Please sign in with Google to continue." */
19
+ message?: string;
20
+ /** Timeout in ms. Default: 300000 */
21
+ timeout?: number;
22
+ /** Custom skip condition. Takes priority over sessionKey check. */
23
+ skipIf?: (c: ToolContext) => boolean | Promise<boolean>;
24
+ /** Called after authentication completes successfully, before next(). */
25
+ onComplete?: (c: ToolContext) => void | Promise<void>;
26
+ }
27
+ /** @deprecated Use `GoogleOptions` instead. */
28
+ type GoogleOAuthOptions = GoogleOptions;
29
+ declare function google(options: GoogleOptions): ToolMiddleware;
30
+ /** @deprecated Use `google()` from `lynq/google` instead. */
31
+ declare const googleOAuth: typeof google;
32
+ interface HandleCallbackOptions {
33
+ clientId: string;
34
+ clientSecret: string;
35
+ redirectUri: string;
36
+ /** Session key for user data. Default: "user" */
37
+ sessionKey?: string;
38
+ }
39
+ /** @deprecated Use `HandleCallbackOptions` instead. */
40
+ type HandleGoogleCallbackOptions = HandleCallbackOptions;
41
+ /**
42
+ * Handle Google OAuth callback. Call from your HTTP callback route.
43
+ * Exchanges code for tokens, fetches user info, stores in session, and completes elicitation.
44
+ */
45
+ declare function handleCallback(server: MCPServer, params: {
46
+ code: string;
47
+ state: string;
48
+ }, options: HandleCallbackOptions): Promise<{
49
+ success: boolean;
50
+ error?: string;
51
+ }>;
52
+ /** @deprecated Use `handleCallback()` from `lynq/google` instead. */
53
+ declare const handleGoogleCallback: typeof handleCallback;
54
+
55
+ export { type GoogleOAuthOptions, type GoogleOptions, type HandleCallbackOptions, type HandleGoogleCallbackOptions, google, googleOAuth, handleCallback, handleGoogleCallback };
@@ -0,0 +1,2 @@
1
+ import {a}from'../chunk-INAAPNKG.mjs';import'../chunk-OYHVJKUP.mjs';import'../chunk-VAAZWX4U.mjs';function g(e){let s=e.scopes??["openid","profile","email"],t={name:e.name??"google",sessionKey:e.sessionKey??"user",message:e.message??"Please sign in with Google to continue.",buildUrl({sessionId:i,elicitationId:r}){return `https://accounts.google.com/o/oauth2/v2/auth?${new URLSearchParams({client_id:e.clientId,redirect_uri:e.redirectUri,response_type:"code",scope:s.join(" "),state:`${i}:${r}`,access_type:"offline"})}`}};return e.timeout!==void 0&&(t.timeout=e.timeout),e.skipIf&&(t.skipIf=e.skipIf),e.onComplete&&(t.onComplete=e.onComplete),a(t)}var f=g;async function p(e,s,t){let i=t.sessionKey??"user",[r,c]=s.state.split(":");if(!r||!c)return {success:false,error:"Invalid state parameter"};try{let o=await(await fetch("https://oauth2.googleapis.com/token",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({code:s.code,client_id:t.clientId,client_secret:t.clientSecret,redirect_uri:t.redirectUri,grant_type:"authorization_code"})})).json();if(!o.access_token)return {success:!1,error:o.error_description??o.error??"Token exchange failed"};let d=await(await fetch("https://www.googleapis.com/oauth2/v2/userinfo",{headers:{Authorization:`Bearer ${o.access_token}`}})).json(),a=e.session(r);return a.set(i,d),a.set("accessToken",o.access_token),o.id_token&&a.set("idToken",o.id_token),e.completeElicitation(c),{success:!0}}catch(n){return {success:false,error:n instanceof Error?n.message:String(n)}}}var h=p;
2
+ export{g as google,f as googleOAuth,p as handleCallback,h as handleGoogleCallback};
@@ -1,4 +1,4 @@
1
- import { t as ToolMiddleware } from '../types-CqT2idkd.js';
1
+ import { v as ToolMiddleware } from '../types-BdFjg9Tn.js';
2
2
  import '@modelcontextprotocol/sdk/types.js';
3
3
  import 'zod';
4
4
 
@@ -1,4 +1,4 @@
1
- import { t as ToolMiddleware } from '../types-CqT2idkd.js';
1
+ import { v as ToolMiddleware } from '../types-BdFjg9Tn.js';
2
2
  import '@modelcontextprotocol/sdk/types.js';
3
3
  import 'zod';
4
4
 
@@ -1,4 +1,4 @@
1
- import { t as ToolMiddleware } from '../types-CqT2idkd.js';
1
+ import { v as ToolMiddleware } from '../types-BdFjg9Tn.js';
2
2
  import '@modelcontextprotocol/sdk/types.js';
3
3
  import 'zod';
4
4
 
@@ -1,4 +1,4 @@
1
- import { t as ToolMiddleware } from '../types-CqT2idkd.js';
1
+ import { s as ToolContext, v as ToolMiddleware } from '../types-BdFjg9Tn.js';
2
2
  import '@modelcontextprotocol/sdk/types.js';
3
3
  import 'zod';
4
4
 
@@ -13,9 +13,15 @@ interface OAuthOptions {
13
13
  buildUrl: (params: {
14
14
  sessionId: string;
15
15
  elicitationId: string;
16
- }) => string;
16
+ }) => string | Promise<string>;
17
17
  /** Timeout in ms. Default: 300000 */
18
18
  timeout?: number;
19
+ /** Use persistent store (userStore) instead of session for state. Default: false */
20
+ persistent?: boolean;
21
+ /** Custom skip condition. Takes priority over sessionKey check. */
22
+ skipIf?: (c: ToolContext) => boolean | Promise<boolean>;
23
+ /** Called after authentication completes successfully, before next(). */
24
+ onComplete?: (c: ToolContext) => void | Promise<void>;
19
25
  }
20
26
  declare function oauth(options: OAuthOptions): ToolMiddleware;
21
27
 
@@ -1 +1 @@
1
- export{a as oauth}from'../chunk-2KEVF6YL.mjs';import'../chunk-STWVQGX5.mjs';import'../chunk-VAAZWX4U.mjs';
1
+ export{a as oauth}from'../chunk-INAAPNKG.mjs';import'../chunk-OYHVJKUP.mjs';import'../chunk-VAAZWX4U.mjs';
@@ -1,4 +1,4 @@
1
- import { t as ToolMiddleware } from '../types-CqT2idkd.js';
1
+ import { s as ToolContext, v as ToolMiddleware } from '../types-BdFjg9Tn.js';
2
2
  import '@modelcontextprotocol/sdk/types.js';
3
3
  import 'zod';
4
4
 
@@ -13,9 +13,15 @@ interface PaymentOptions {
13
13
  buildUrl: (params: {
14
14
  sessionId: string;
15
15
  elicitationId: string;
16
- }) => string;
16
+ }) => string | Promise<string>;
17
17
  /** Timeout in ms. Default: 300000 */
18
18
  timeout?: number;
19
+ /** Use persistent store (userStore) instead of session for state. Default: false */
20
+ persistent?: boolean;
21
+ /** Custom skip condition. Takes priority over sessionKey check. */
22
+ skipIf?: (c: ToolContext) => boolean | Promise<boolean>;
23
+ /** Called after payment completes successfully, before next(). */
24
+ onComplete?: (c: ToolContext) => void | Promise<void>;
19
25
  }
20
26
  declare function payment(options: PaymentOptions): ToolMiddleware;
21
27
 
@@ -1 +1 @@
1
- import {a}from'../chunk-STWVQGX5.mjs';import'../chunk-VAAZWX4U.mjs';function i(e){let t={name:e.name??"payment",sessionKey:e.sessionKey??"payment",message:e.message??"Please complete payment to continue.",buildUrl:e.buildUrl,declineMessage:"Payment cancelled."};return e.timeout!==void 0&&(t.timeout=e.timeout),a(t)}export{i as payment};
1
+ export{a as payment}from'../chunk-BVDKAIOU.mjs';import'../chunk-OYHVJKUP.mjs';import'../chunk-VAAZWX4U.mjs';
@@ -1,4 +1,4 @@
1
- import { t as ToolMiddleware } from '../types-CqT2idkd.js';
1
+ import { v as ToolMiddleware } from '../types-BdFjg9Tn.js';
2
2
  import '@modelcontextprotocol/sdk/types.js';
3
3
  import 'zod';
4
4
 
@@ -0,0 +1,60 @@
1
+ import { s as ToolContext, M as MCPServer, v as ToolMiddleware } from '../types-BdFjg9Tn.js';
2
+ import '@modelcontextprotocol/sdk/types.js';
3
+ import 'zod';
4
+
5
+ interface StripeOptions {
6
+ /** Middleware name. Default: "stripe" */
7
+ name?: string;
8
+ /** Stripe secret key (server-side). */
9
+ secretKey: string;
10
+ /** Base URL of your server (for callback URLs). */
11
+ baseUrl: string;
12
+ /** Callback path. Default: "/payment/stripe/callback" */
13
+ callbackPath?: string;
14
+ /** Price in cents (USD). e.g., 100 = $1.00 */
15
+ amount: number;
16
+ /** Currency. Default: "usd" */
17
+ currency?: string;
18
+ /** Product description shown on Stripe Checkout. */
19
+ description?: string;
20
+ /** Session key for payment data. Default: "payment" */
21
+ sessionKey?: string;
22
+ /** If true, only charge once per session per tool. Default: false */
23
+ once?: boolean;
24
+ /** Message shown to user. */
25
+ message?: string;
26
+ /** Timeout in ms. Default: 300000 */
27
+ timeout?: number;
28
+ /** Custom skip condition. Takes priority over sessionKey check. */
29
+ skipIf?: (c: ToolContext) => boolean | Promise<boolean>;
30
+ /** Called after payment completes successfully, before next(). */
31
+ onComplete?: (c: ToolContext) => void | Promise<void>;
32
+ }
33
+ /** @deprecated Use `StripeOptions` instead. */
34
+ type StripePaymentOptions = StripeOptions;
35
+ declare function stripe(options: StripeOptions): ToolMiddleware;
36
+ /** @deprecated Use `stripe()` from `lynq/stripe` instead. */
37
+ declare const stripePayment: typeof stripe;
38
+ interface HandleCallbackOptions {
39
+ /** Stripe secret key. */
40
+ secretKey: string;
41
+ /** Session key. Default: "payment" */
42
+ sessionKey?: string;
43
+ }
44
+ /** @deprecated Use `HandleCallbackOptions` instead. */
45
+ type HandleStripeCallbackOptions = HandleCallbackOptions;
46
+ /**
47
+ * Handle Stripe Checkout callback. Call from your HTTP callback route.
48
+ * Retrieves the Checkout Session, verifies payment, stores in session, and completes elicitation.
49
+ */
50
+ declare function handleCallback(server: MCPServer, params: {
51
+ checkoutSessionId: string;
52
+ state: string;
53
+ }, options: HandleCallbackOptions): Promise<{
54
+ success: boolean;
55
+ error?: string;
56
+ }>;
57
+ /** @deprecated Use `handleCallback()` from `lynq/stripe` instead. */
58
+ declare const handleStripeCallback: typeof handleCallback;
59
+
60
+ export { type HandleCallbackOptions, type HandleStripeCallbackOptions, type StripeOptions, type StripePaymentOptions, handleCallback, handleStripeCallback, stripe, stripePayment };
@@ -0,0 +1 @@
1
+ import {a}from'../chunk-BVDKAIOU.mjs';import'../chunk-OYHVJKUP.mjs';import'../chunk-VAAZWX4U.mjs';function S(e){let{secretKey:o,baseUrl:n,callbackPath:a$1="/payment/stripe/callback",amount:r,currency:i="usd",description:t,once:m=false}=e,s=e.name??"stripe",u=e.sessionKey??"payment",b=e.message??`Payment required ($${(r/100).toFixed(2)}).`,c={name:s,sessionKey:u,message:b,async buildUrl({sessionId:l,elicitationId:p}){let g=(await import('stripe')).default,k=new g(o),y=`${l}:${p}`;return (await k.checkout.sessions.create({payment_method_types:["card"],line_items:[{price_data:{currency:i,product_data:{name:t??"Tool access"},unit_amount:r},quantity:1}],mode:"payment",success_url:`${n}${a$1}?session_id={CHECKOUT_SESSION_ID}&state=${y}`,cancel_url:`${n}${a$1}?cancelled=true&state=${y}`,metadata:{sessionId:l,elicitationId:p}})).url??""}};e.timeout!==void 0&&(c.timeout=e.timeout),e.skipIf&&(c.skipIf=e.skipIf),e.onComplete&&(c.onComplete=e.onComplete);let d=a(c);return m?d:{...d,onResult(l,p){return p.session.set(u,void 0),l}}}var x=S;async function C(e,o,n){let a=n.sessionKey??"payment",[r,i]=o.state.split(":");if(!r||!i)return {success:false,error:"Invalid state parameter"};try{let t=(await import('stripe')).default,s=await new t(n.secretKey).checkout.sessions.retrieve(o.checkoutSessionId);return s.payment_status!=="paid"?{success:!1,error:"Payment not completed"}:(e.session(r).set(a,{provider:"stripe",checkoutSessionId:s.id,amount:s.amount_total,currency:s.currency,paidAt:new Date().toISOString()}),e.completeElicitation(i),{success:!0})}catch(t){return {success:false,error:t instanceof Error?t.message:String(t)}}}var P=C;export{C as handleCallback,P as handleStripeCallback,S as stripe,x as stripePayment};
@@ -0,0 +1,15 @@
1
+ import { v as ToolMiddleware } from '../types-BdFjg9Tn.js';
2
+ import '@modelcontextprotocol/sdk/types.js';
3
+ import 'zod';
4
+
5
+ interface TipOptions {
6
+ /** Middleware name. Default: "tip" */
7
+ name?: string;
8
+ /** Build the tip URL. Receives sessionId. */
9
+ url: (sessionId: string) => string;
10
+ /** Message shown to user. Default: "If this was helpful, consider leaving a tip!" */
11
+ message?: string;
12
+ }
13
+ declare function tip(options: TipOptions): ToolMiddleware;
14
+
15
+ export { type TipOptions, tip };
@@ -0,0 +1,4 @@
1
+ function o(t){let n=t.name??"tip",s=t.message??"If this was helpful, consider leaving a tip!";return {name:n,onResult(e,i){if(e.isError)return e;let r=t.url(i.sessionId);return {...e,content:[...e.content??[],{type:"text",text:`
2
+
3
+ ${s}
4
+ ${r}`}]}}}}export{o as tip};
@@ -1,4 +1,4 @@
1
- import { t as ToolMiddleware } from '../types-CqT2idkd.js';
1
+ import { v as ToolMiddleware } from '../types-BdFjg9Tn.js';
2
2
  import '@modelcontextprotocol/sdk/types.js';
3
3
  import 'zod';
4
4
 
@@ -1,4 +1,4 @@
1
- import { t as ToolMiddleware } from '../types-CqT2idkd.js';
1
+ import { s as ToolContext, v as ToolMiddleware } from '../types-BdFjg9Tn.js';
2
2
  import '@modelcontextprotocol/sdk/types.js';
3
3
  import 'zod';
4
4
 
@@ -13,11 +13,17 @@ interface UrlActionOptions {
13
13
  buildUrl: (params: {
14
14
  sessionId: string;
15
15
  elicitationId: string;
16
- }) => string;
16
+ }) => string | Promise<string>;
17
17
  /** Timeout in ms for waiting for external callback. Default: 300000 (5 min). */
18
18
  timeout?: number;
19
19
  /** Error message when user declines. Default: "Action cancelled." */
20
20
  declineMessage?: string;
21
+ /** Use persistent store (userStore) instead of session for state. Default: false */
22
+ persistent?: boolean;
23
+ /** Custom skip condition. If returns true, skip the elicitation and call next(). Takes priority over sessionKey check. */
24
+ skipIf?: (c: ToolContext) => boolean | Promise<boolean>;
25
+ /** Called after elicitation completes successfully, before next(). */
26
+ onComplete?: (c: ToolContext) => void | Promise<void>;
21
27
  }
22
28
  declare function urlAction(options: UrlActionOptions): ToolMiddleware;
23
29
 
@@ -1 +1 @@
1
- export{a as urlAction}from'../chunk-STWVQGX5.mjs';import'../chunk-VAAZWX4U.mjs';
1
+ export{a as urlAction}from'../chunk-OYHVJKUP.mjs';import'../chunk-VAAZWX4U.mjs';
@@ -0,0 +1,26 @@
1
+ interface GitHubPagesConfig {
2
+ clientId: string;
3
+ clientSecret: string;
4
+ sessionKey?: string;
5
+ }
6
+ interface GooglePagesConfig {
7
+ clientId: string;
8
+ clientSecret: string;
9
+ sessionKey?: string;
10
+ }
11
+ interface StripePagesConfig {
12
+ secretKey: string;
13
+ sessionKey?: string;
14
+ }
15
+ interface CryptoPagesConfig {
16
+ rpcUrl?: string;
17
+ sessionKey?: string;
18
+ }
19
+ interface PagesConfig {
20
+ github?: true | string | GitHubPagesConfig;
21
+ google?: true | string | GooglePagesConfig;
22
+ stripe?: true | string | StripePagesConfig;
23
+ crypto?: true | string | CryptoPagesConfig;
24
+ }
25
+
26
+ export type { PagesConfig as P };
@@ -0,0 +1 @@
1
+ export{d as cryptoPaymentPage,c as errorPage,a as escapeHtml,h as handleCryptoGet,i as handleCryptoPost,e as handleGitHubPage,f as handleGooglePage,g as handleStripePage,b as successPage}from'./chunk-OJJZGR4B.mjs';
@@ -0,0 +1,9 @@
1
+ import { n as Store, m as Session, U as UserStore } from './types-BdFjg9Tn.js';
2
+ import '@modelcontextprotocol/sdk/types.js';
3
+ import 'zod';
4
+
5
+ declare function memoryStore(): Store;
6
+ declare function resolveUserId(session: Session): string | undefined;
7
+ declare function createUserStore(session: Session, store: Store): UserStore;
8
+
9
+ export { createUserStore, memoryStore, resolveUserId };
package/dist/store.mjs ADDED
@@ -0,0 +1 @@
1
+ export{c as createUserStore,a as memoryStore,b as resolveUserId}from'./chunk-SPZY5GJA.mjs';
package/dist/test.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { CallToolResult } from '@modelcontextprotocol/sdk/types.js';
2
- import { l as Session, M as MCPServer } from './types-CqT2idkd.js';
2
+ import { m as Session, M as MCPServer } from './types-BdFjg9Tn.js';
3
3
  import 'zod';
4
4
 
5
5
  interface TestClient {
@@ -20,6 +20,15 @@ interface ServerInfo {
20
20
  name: string;
21
21
  version: string;
22
22
  }
23
+ interface Store {
24
+ get<T = unknown>(key: string): Promise<T | undefined>;
25
+ set(key: string, value: unknown, ttl?: number): Promise<void>;
26
+ delete(key: string): Promise<void>;
27
+ }
28
+ type UserStore = Store;
29
+ interface ServerOptions extends ServerInfo {
30
+ store?: Store;
31
+ }
23
32
  interface Session {
24
33
  /** Get a session-scoped value. */
25
34
  get<T = unknown>(key: string): T | undefined;
@@ -104,6 +113,10 @@ interface ToolContext {
104
113
  error(message: string): ToolResponse;
105
114
  /** Create an image response. Chainable. */
106
115
  image(data: string, mimeType: string): ToolResponse;
116
+ /** Persistent key-value store (global scope). */
117
+ store: Store;
118
+ /** Persistent key-value store (user scope, keyed by session user ID). */
119
+ userStore: UserStore;
107
120
  }
108
121
  interface ToolInfo {
109
122
  name: string;
@@ -160,6 +173,10 @@ interface ResourceContext {
160
173
  sessionId: string;
161
174
  /** Query client-provided filesystem roots. */
162
175
  roots: () => Promise<RootInfo[]>;
176
+ /** Persistent key-value store (global scope). */
177
+ store: Store;
178
+ /** Persistent key-value store (user scope, keyed by session user ID). */
179
+ userStore: UserStore;
163
180
  }
164
181
  type ResourceHandler = (uri: string, c: ResourceContext) => ResourceContent | Promise<ResourceContent>;
165
182
  interface HttpAdapterOptions {
@@ -195,6 +212,8 @@ interface MCPServer {
195
212
  session(sessionId: string): Session;
196
213
  /** Complete a pending URL elicitation (called from external HTTP callback). */
197
214
  completeElicitation(elicitationId: string): void;
215
+ /** The persistent store instance. */
216
+ store: Store;
198
217
  }
199
218
 
200
- export { type Elicit as E, type HttpAdapterOptions as H, type MCPServer as M, type ResourceConfig as R, type Sample as S, type TaskConfig as T, type ElicitFormResult as a, type ElicitUrlOptions as b, type ElicitUrlResult as c, type ResourceContent as d, type ResourceContext as e, type ResourceHandler as f, type RootInfo as g, type SampleOptions as h, type SampleRawParams as i, type SampleRawResult as j, type ServerInfo as k, type Session as l, type TaskContext as m, type TaskControl as n, type TaskHandler as o, type ToolConfig as p, type ToolContext as q, type ToolHandler as r, type ToolInfo as s, type ToolMiddleware as t, type ToolResponse as u, error as v, image as w, json as x, text as y };
219
+ export { text as A, type Elicit as E, type HttpAdapterOptions as H, type MCPServer as M, type ResourceConfig as R, type ServerOptions as S, type TaskConfig as T, type UserStore as U, type ElicitFormResult as a, type ElicitUrlOptions as b, type ElicitUrlResult as c, type ResourceContent as d, type ResourceContext as e, type ResourceHandler as f, type RootInfo as g, type Sample as h, type SampleOptions as i, type SampleRawParams as j, type SampleRawResult as k, type ServerInfo as l, type Session as m, type Store as n, type TaskContext as o, type TaskControl as p, type TaskHandler as q, type ToolConfig as r, type ToolContext as s, type ToolHandler as t, type ToolInfo as u, type ToolMiddleware as v, type ToolResponse as w, error as x, image as y, json as z };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lynq/lynq",
3
- "version": "0.4.0",
3
+ "version": "0.6.0",
4
4
  "description": "Lightweight MCP server framework. Tool visibility control through middleware.",
5
5
  "type": "module",
6
6
  "exports": {
@@ -72,13 +72,41 @@
72
72
  "types": "./dist/middleware/jwt.d.ts",
73
73
  "import": "./dist/middleware/jwt.mjs"
74
74
  },
75
+ "./github": {
76
+ "types": "./dist/middleware/github.d.ts",
77
+ "import": "./dist/middleware/github.mjs"
78
+ },
75
79
  "./github-oauth": {
76
- "types": "./dist/middleware/github-oauth.d.ts",
77
- "import": "./dist/middleware/github-oauth.mjs"
80
+ "types": "./dist/middleware/github.d.ts",
81
+ "import": "./dist/middleware/github.mjs"
82
+ },
83
+ "./google": {
84
+ "types": "./dist/middleware/google.d.ts",
85
+ "import": "./dist/middleware/google.mjs"
78
86
  },
79
87
  "./google-oauth": {
80
- "types": "./dist/middleware/google-oauth.d.ts",
81
- "import": "./dist/middleware/google-oauth.mjs"
88
+ "types": "./dist/middleware/google.d.ts",
89
+ "import": "./dist/middleware/google.mjs"
90
+ },
91
+ "./stripe": {
92
+ "types": "./dist/middleware/stripe.d.ts",
93
+ "import": "./dist/middleware/stripe.mjs"
94
+ },
95
+ "./crypto": {
96
+ "types": "./dist/middleware/crypto.d.ts",
97
+ "import": "./dist/middleware/crypto.mjs"
98
+ },
99
+ "./usdc": {
100
+ "types": "./dist/middleware/crypto.d.ts",
101
+ "import": "./dist/middleware/crypto.mjs"
102
+ },
103
+ "./tip": {
104
+ "types": "./dist/middleware/tip.d.ts",
105
+ "import": "./dist/middleware/tip.mjs"
106
+ },
107
+ "./store": {
108
+ "types": "./dist/store.d.ts",
109
+ "import": "./dist/store.mjs"
82
110
  }
83
111
  },
84
112
  "files": [
@@ -107,6 +135,7 @@
107
135
  "express": "^5.2.1",
108
136
  "hono": "^4.12.5",
109
137
  "jose": "^6.2.1",
138
+ "stripe": "^20.4.1",
110
139
  "tsup": "^8.0.0",
111
140
  "typedoc": "^0.28.17",
112
141
  "typedoc-plugin-markdown": "^4.10.0",
@@ -119,6 +148,7 @@
119
148
  "express": "^5.0.0",
120
149
  "hono": "^4.0.0",
121
150
  "jose": "^6.0.0",
151
+ "stripe": "^17.0.0 || ^18.0.0 || ^19.0.0 || ^20.0.0",
122
152
  "zod": "^3.0.0"
123
153
  },
124
154
  "peerDependenciesMeta": {
@@ -133,6 +163,9 @@
133
163
  },
134
164
  "jose": {
135
165
  "optional": true
166
+ },
167
+ "stripe": {
168
+ "optional": true
136
169
  }
137
170
  },
138
171
  "publishConfig": {
@@ -1 +0,0 @@
1
- import {a}from'./chunk-STWVQGX5.mjs';function n(e){let t={name:e.name??"oauth",sessionKey:e.sessionKey??"user",message:e.message??"Please sign in to continue.",buildUrl:e.buildUrl,declineMessage:"Authentication cancelled."};return e.timeout!==void 0&&(t.timeout=e.timeout),a(t)}export{n as a};
@@ -1 +0,0 @@
1
- import {c}from'./chunk-VAAZWX4U.mjs';function m(e){let n=e.name??"url-action",i=e.sessionKey??"user",l=e.timeout??3e5,a=e.declineMessage??"Action cancelled.";return {name:n,onRegister(){return false},async onCall(s,r){if(s.session.get(i))return r();let o=crypto.randomUUID(),c$1=e.buildUrl({sessionId:s.sessionId,elicitationId:o});return (await s.elicit.url(e.message,c$1,{elicitationId:o,waitForCompletion:true,timeout:l})).action!=="accept"?c(a):s.session.get(i)?(s.session.authorize(n),r()):c("Action was not completed.")}}}export{m as a};
@@ -1,42 +0,0 @@
1
- import { t as ToolMiddleware, M as MCPServer } from '../types-CqT2idkd.js';
2
- import '@modelcontextprotocol/sdk/types.js';
3
- import 'zod';
4
-
5
- interface GitHubOAuthOptions {
6
- /** Middleware name. Default: "github-oauth" */
7
- name?: string;
8
- /** GitHub OAuth App client ID. */
9
- clientId: string;
10
- /** GitHub OAuth App client secret. */
11
- clientSecret: string;
12
- /** OAuth callback URL (your server's callback endpoint). */
13
- redirectUri: string;
14
- /** GitHub OAuth scopes. Default: [] */
15
- scopes?: string[];
16
- /** Session key for user data. Default: "user" */
17
- sessionKey?: string;
18
- /** Message shown to the user. Default: "Please sign in with GitHub to continue." */
19
- message?: string;
20
- /** Timeout in ms. Default: 300000 */
21
- timeout?: number;
22
- }
23
- declare function githubOAuth(options: GitHubOAuthOptions): ToolMiddleware;
24
- interface HandleGitHubCallbackOptions {
25
- clientId: string;
26
- clientSecret: string;
27
- /** Session key for user data. Default: "user" */
28
- sessionKey?: string;
29
- }
30
- /**
31
- * Handle GitHub OAuth callback. Call from your HTTP callback route.
32
- * Exchanges code for token, fetches user info, stores in session, and completes elicitation.
33
- */
34
- declare function handleGitHubCallback(server: MCPServer, params: {
35
- code: string;
36
- state: string;
37
- }, options: HandleGitHubCallbackOptions): Promise<{
38
- success: boolean;
39
- error?: string;
40
- }>;
41
-
42
- export { type GitHubOAuthOptions, type HandleGitHubCallbackOptions, githubOAuth, handleGitHubCallback };
@@ -1,2 +0,0 @@
1
- import {a}from'../chunk-2KEVF6YL.mjs';import'../chunk-STWVQGX5.mjs';import'../chunk-VAAZWX4U.mjs';function h(e){let s=e.scopes??[],t={name:e.name??"github-oauth",sessionKey:e.sessionKey??"user",message:e.message??"Please sign in with GitHub to continue.",buildUrl({sessionId:c,elicitationId:n}){let r=new URLSearchParams({client_id:e.clientId,redirect_uri:e.redirectUri,state:`${c}:${n}`});return s.length>0&&r.set("scope",s.join(" ")),`https://github.com/login/oauth/authorize?${r}`}};return e.timeout!==void 0&&(t.timeout=e.timeout),a(t)}async function m(e,s,t){let c=t.sessionKey??"user",[n,r]=s.state.split(":");if(!n||!r)return {success:false,error:"Invalid state parameter"};try{let i=await(await fetch("https://github.com/login/oauth/access_token",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({client_id:t.clientId,client_secret:t.clientSecret,code:s.code})})).json();if(!i.access_token)return {success:!1,error:i.error_description??i.error??"Token exchange failed"};let l=await(await fetch("https://api.github.com/user",{headers:{Authorization:`Bearer ${i.access_token}`}})).json(),a=e.session(n);return a.set(c,l),a.set("accessToken",i.access_token),e.completeElicitation(r),{success:!0}}catch(o){return {success:false,error:o instanceof Error?o.message:String(o)}}}
2
- export{h as githubOAuth,m as handleGitHubCallback};
@@ -1,43 +0,0 @@
1
- import { t as ToolMiddleware, M as MCPServer } from '../types-CqT2idkd.js';
2
- import '@modelcontextprotocol/sdk/types.js';
3
- import 'zod';
4
-
5
- interface GoogleOAuthOptions {
6
- /** Middleware name. Default: "google-oauth" */
7
- name?: string;
8
- /** Google OAuth client ID. */
9
- clientId: string;
10
- /** Google OAuth client secret. */
11
- clientSecret: string;
12
- /** OAuth callback URL (your server's callback endpoint). */
13
- redirectUri: string;
14
- /** OAuth scopes. Default: ["openid", "profile", "email"] */
15
- scopes?: string[];
16
- /** Session key for user data. Default: "user" */
17
- sessionKey?: string;
18
- /** Message shown to the user. Default: "Please sign in with Google to continue." */
19
- message?: string;
20
- /** Timeout in ms. Default: 300000 */
21
- timeout?: number;
22
- }
23
- declare function googleOAuth(options: GoogleOAuthOptions): ToolMiddleware;
24
- interface HandleGoogleCallbackOptions {
25
- clientId: string;
26
- clientSecret: string;
27
- redirectUri: string;
28
- /** Session key for user data. Default: "user" */
29
- sessionKey?: string;
30
- }
31
- /**
32
- * Handle Google OAuth callback. Call from your HTTP callback route.
33
- * Exchanges code for tokens, fetches user info, stores in session, and completes elicitation.
34
- */
35
- declare function handleGoogleCallback(server: MCPServer, params: {
36
- code: string;
37
- state: string;
38
- }, options: HandleGoogleCallbackOptions): Promise<{
39
- success: boolean;
40
- error?: string;
41
- }>;
42
-
43
- export { type GoogleOAuthOptions, type HandleGoogleCallbackOptions, googleOAuth, handleGoogleCallback };
@@ -1,2 +0,0 @@
1
- import {a}from'../chunk-2KEVF6YL.mjs';import'../chunk-STWVQGX5.mjs';import'../chunk-VAAZWX4U.mjs';function m(e){let r=e.scopes??["openid","profile","email"],t={name:e.name??"google-oauth",sessionKey:e.sessionKey??"user",message:e.message??"Please sign in with Google to continue.",buildUrl({sessionId:i,elicitationId:o}){return `https://accounts.google.com/o/oauth2/v2/auth?${new URLSearchParams({client_id:e.clientId,redirect_uri:e.redirectUri,response_type:"code",scope:r.join(" "),state:`${i}:${o}`,access_type:"offline"})}`}};return e.timeout!==void 0&&(t.timeout=e.timeout),a(t)}async function p(e,r,t){let i=t.sessionKey??"user",[o,c]=r.state.split(":");if(!o||!c)return {success:false,error:"Invalid state parameter"};try{let s=await(await fetch("https://oauth2.googleapis.com/token",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({code:r.code,client_id:t.clientId,client_secret:t.clientSecret,redirect_uri:t.redirectUri,grant_type:"authorization_code"})})).json();if(!s.access_token)return {success:!1,error:s.error_description??s.error??"Token exchange failed"};let d=await(await fetch("https://www.googleapis.com/oauth2/v2/userinfo",{headers:{Authorization:`Bearer ${s.access_token}`}})).json(),a=e.session(o);return a.set(i,d),a.set("accessToken",s.access_token),s.id_token&&a.set("idToken",s.id_token),e.completeElicitation(c),{success:!0}}catch(n){return {success:false,error:n instanceof Error?n.message:String(n)}}}
2
- export{m as googleOAuth,p as handleGoogleCallback};