@tempo-ai/mcp 0.0.157 → 0.0.158-staging.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +10 -6
- package/dist/bin.js +1 -1
- package/dist/call-35TEN5BZ.js +1 -0
- package/dist/chunk-7NGSCREN.js +1 -0
- package/dist/chunk-DRKOQGDA.js +1 -0
- package/dist/chunk-G2Z7BCZL.js +1 -0
- package/dist/chunk-RM7FBC6B.js +10 -0
- package/dist/index.js +1 -1
- package/dist/serve-ITS7X53Y.js +399 -0
- package/package.json +1 -1
- package/dist/call-GVSFO6WO.js +0 -1
- package/dist/chunk-F6FX3DG7.js +0 -1
- package/dist/chunk-M22S2I46.js +0 -1
- package/dist/serve-QKEMBDNI.js +0 -408
- package/dist/token-O44QDXRT.js +0 -1
package/README.md
CHANGED
|
@@ -51,13 +51,17 @@ Cursor / generic JSON config:
|
|
|
51
51
|
```
|
|
52
52
|
|
|
53
53
|
Then just use a Tempo tool ("list my Tempo issues"). The first one that
|
|
54
|
-
needs your account
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
54
|
+
needs your account shows a sign-in link and a short code (and opens the
|
|
55
|
+
browser when it can). Approve on any device — this machine, or your phone
|
|
56
|
+
for a remote box — and the tool continues. No login command, no restart.
|
|
57
|
+
Later sessions connect silently: the sign-in is standard OAuth and renews
|
|
58
|
+
itself, so you only sign in again after `logout` or if you revoke it.
|
|
58
59
|
|
|
59
|
-
Optional: sign in ahead of time with `npx -y @tempo-ai/mcp login
|
|
60
|
-
|
|
60
|
+
Optional: sign in ahead of time with `npx -y @tempo-ai/mcp login`.
|
|
61
|
+
|
|
62
|
+
Unattended environments (CI, scheduled jobs, sandboxes wiped every run)
|
|
63
|
+
aren't supported: there's nobody to approve a sign-in, and personal access
|
|
64
|
+
tokens were removed.
|
|
61
65
|
|
|
62
66
|
### Flags
|
|
63
67
|
|
package/dist/bin.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{createRequire as
|
|
2
|
+
import{createRequire as r}from"node:module";r(import.meta.url);import{run as e}from"./chunk-G2Z7BCZL.js";import"./chunk-7NGSCREN.js";import"./chunk-DRKOQGDA.js";import"./chunk-NCFWHGWN.js";e(process.argv).then(r=>{process.exitCode=r},r=>{console.error(r instanceof Error?r.stack||r.message:r),process.exitCode=1});
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{createRequire as t}from"node:module";t(import.meta.url);import{ensureCliAuth as o}from"./chunk-7NGSCREN.js";import{manifestFor as e}from"./chunk-RM7FBC6B.js";import{parseServeArgs as r}from"./chunk-DRKOQGDA.js";import"./chunk-NCFWHGWN.js";import{Client as n}from"@modelcontextprotocol/sdk/client/index.js";import{InMemoryTransport as s}from"@modelcontextprotocol/sdk/inMemory.js";async function connectAggregate(t){const{createTempoAggregate:o}=await(import("./serve-ITS7X53Y.js")),e=await o(t,{stageDocuments:!1}),[r,i]=s.createLinkedPair(),a=new n({name:"tempo-mcp-cli",version:"0"});return await e.aggregate.connect(i),await a.connect(r),{client:a,dispose:async()=>{await a.close(),await e.dispose()}}}function extractFlag(t,o){const e=t.filter(t=>t!==o);return{present:e.length!==t.length,rest:e}}async function runTools(t){const{present:o,rest:e}=extractFlag(t,"--schemas"),n=r(e);if("error"in n)return console.error(n.error),1;const{client:s,dispose:i}=await connectAggregate(n);try{const{tools:t}=await s.listTools(),e=t.map(t=>o?{name:t.name,description:t.description,inputSchema:t.inputSchema}:{name:t.name,description:t.description});return console.log(JSON.stringify({tools:e},null,2)),0}finally{await i()}}async function runCall(t){const[n,...s]=t;if(!n||n.startsWith("--"))return console.error('Usage: tempo-mcp call <tool> --json \'{"orgId": "...", ...}\'\nDiscover tools and their schemas with `tempo-mcp tools --schemas`.'),1;let i=null;const a=[];for(let t=0;t<s.length;t++)"--json"===s[t]?i=s[++t]??null:a.push(s[t]);let c={};if(null!=i){"-"===i&&(i=await readStdin());try{const t=JSON.parse(i);if(null===t||"object"!=typeof t||Array.isArray(t))return console.error("--json must be a JSON object of tool arguments"),1;c=t}catch(t){return console.error(`--json is not valid JSON: ${t instanceof Error?t.message:String(t)}`),1}}const l=r(a);if("error"in l)return console.error(l.error),1;const{toolRequiresAuth:m}=await(import("./serve-ITS7X53Y.js")),u=e(n)?.toolset;(void 0===u||m(u,n))&&await o();const{client:p,dispose:f}=await connectAggregate(l);try{const t=await p.callTool({name:n,arguments:c}),o=Array.isArray(t.content)?t.content:[];for(const t of o)"text"===t.type?console.log(t.text):console.log(JSON.stringify(t));return t.isError?1:0}finally{await f()}}function readStdin(){return new Promise((t,o)=>{const e=[];process.stdin.on("data",t=>e.push(Buffer.from(t))),process.stdin.on("end",()=>t(Buffer.concat(e).toString("utf8"))),process.stdin.on("error",o)})}export{runCall,runTools};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{createRequire as n}from"node:module";n(import.meta.url);import{createRefreshLoop as e,openInBrowser as o,readAuth as i,resolveConvexSiteUrl as t,resolveConvexUrl as r,startDeviceSignIn as s}from"./chunk-DRKOQGDA.js";async function signInInteractively(){let n;try{n=await s({convexSiteUrl:t(r())})}catch(n){return console.error("Couldn't start sign-in:",n instanceof Error?n.message:String(n)),1}const e=await o(n.signInUrl);console.log(e?"Opened your browser to sign in to Tempo. If it didn't open, visit this link on any device:":"Sign in to Tempo by visiting this link on any device:"),console.log(` ${n.signInUrl}`),console.log(""),console.log(`Check the page shows this code, then approve: ${n.userCode}`),console.log(""),console.log("Waiting for approval (the link works for 10 minutes)...");try{await n.done;const e=await i();return console.log(""),console.log(`Signed in as ${e?.email??e?.userId??"unknown user"}.`),console.log("Credentials stored in ~/.tempo/auth.json (0600)."),0}catch(n){return console.error("Sign-in failed:",n instanceof Error?n.message:n),1}}async function runLogin(){const n=await i();return n&&n.expiresAt-Date.now()>6e4?(console.log(`Already signed in as ${n.email??n.userId}. Run \`tempo-mcp logout\` first to sign in as someone else.`),0):signInInteractively()}var a=class extends Error{constructor(){super("Not signed in to Tempo. Run `npx -y @tempo-ai/mcp login` in a terminal (it shows a link you can approve from any device)."),this.name="NotSignedInError"}};async function ensureCliAuth(){const n=t(r()),o=await i();if(o&&o.expiresAt-Date.now()<=6e4){const o=e({convexSiteUrl:n,onReauthRequired:()=>{}});await o.refreshNow()}if(!await i()){if(!process.stdout.isTTY)throw new a;if(0!==await signInInteractively())throw new a}}function warnIfLegacyTokenEnv(){process.env.TEMPO_AUTH_TOKEN?.trim()&&console.error("[tempo-mcp] TEMPO_AUTH_TOKEN is no longer supported and is ignored: personal access tokens were removed. Sign in with `npx -y @tempo-ai/mcp login` (it shows a link you can approve from any device).")}export{runLogin,a as NotSignedInError,ensureCliAuth,warnIfLegacyTokenEnv};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{createRequire as e}from"node:module";e(import.meta.url);import t from"fs";import n from"fs/promises";import r from"path";import o from"os";import s from"path";function tempoHome(){return process.env.TEMPO_MCP_HOME??s.join(o.homedir(),".tempo")}function authFilePath(){return s.join(tempoHome(),"auth.json")}function logsDir(){return s.join(tempoHome(),"logs")}function logFilePath(e){const t=(new Date).toISOString().slice(0,10);return s.join(logsDir(),`mcp-${e}-${t}.log`)}async function readAuth(){try{const e=await n.readFile(authFilePath(),"utf8"),t=JSON.parse(e);return"string"==typeof t.token&&"string"==typeof t.sessionId&&"string"==typeof t.userId&&"number"==typeof t.expiresAt?t:null}catch(e){return e.code,null}}function readAuthSync(){try{const e=t.readFileSync(authFilePath(),"utf8"),n=JSON.parse(e);return"string"==typeof n.token&&"string"==typeof n.sessionId&&"string"==typeof n.userId&&"number"==typeof n.expiresAt?n:null}catch{return null}}async function writeAuth(e){const t=tempoHome();await n.mkdir(t,{recursive:!0,mode:448});const o=authFilePath(),s=r.join(t,`auth.json.tmp.${process.pid}.${Date.now()}`),i=JSON.stringify(e,null,2);await n.writeFile(s,i,{mode:384}),await n.rename(s,o);try{await n.chmod(o,384)}catch{}}async function clearAuth(){try{await n.unlink(authFilePath())}catch(e){if("ENOENT"!==e.code)throw e}}import i from"fs/promises";import a from"path";function authLockPath(){return a.join(tempoHome(),"auth.lock")}async function withAuthLock(e,t={}){const n=t.timeoutMs??6e4,r=t.staleMs??12e4,o=authLockPath();await i.mkdir(tempoHome(),{recursive:!0,mode:448});const s=Date.now()+n;for(;;){try{await i.mkdir(o);break}catch(e){if("EEXIST"!==e.code)throw e}const e=await i.stat(o).catch(()=>null);if(e)if(Date.now()-e.mtimeMs>r)await breakIfStale(o,r);else{if(Date.now()>=s)throw new Error(`Timed out waiting for another Tempo process to finish signing in (${o}).`);await new Promise(e=>setTimeout(e,50+100*Math.random()))}}try{return await e()}finally{await i.rm(o,{recursive:!0,force:!0}).catch(()=>{})}}async function breakIfStale(e,t){const n=`${e}.break`;try{await i.mkdir(n)}catch(e){if("EEXIST"!==e.code)throw e;const t=await i.stat(n).catch(()=>null);return void(t&&Date.now()-t.mtimeMs>1e4&&await i.rm(n,{recursive:!0,force:!0}).catch(()=>{}))}try{const n=await i.stat(e).catch(()=>null);n&&Date.now()-n.mtimeMs>t&&await i.rm(e,{recursive:!0,force:!0})}finally{await i.rm(n,{recursive:!0,force:!0}).catch(()=>{})}}function decodeJwtExp(e){try{const[,t]=e.split("."),n=JSON.parse(Buffer.from(t,"base64").toString("utf8"));if("number"==typeof n.exp)return 1e3*n.exp}catch{}return Date.now()+3e5}var c={issuer:"https://clerk.auth.tempo.build",clientId:"cYQe5GCuSjRScRJ5"},u="openid profile email offline_access";function resolveOAuthConfig(){const e=process.env.TEMPO_OAUTH_ISSUER?.trim(),t=process.env.TEMPO_OAUTH_CLIENT_ID?.trim();if(!e&&!t)return c;if(!e||!t)throw new Error("TEMPO_OAUTH_ISSUER and TEMPO_OAUTH_CLIENT_ID must be set together.");return{issuer:e.replace(/\/+$/,""),clientId:t}}var l=15e3,d=class extends Error{constructor(e,t,n){super(e),this.name="OAuthError",this.code=t,this.terminal=n}};async function postForm(e,t){let n;try{n=await fetch(e,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString(),signal:AbortSignal.timeout(l)})}catch(e){throw new d(`Couldn't reach Tempo sign-in: ${e instanceof Error?e.message:String(e)}`,"network",!1)}let r={};try{r=await n.json()}catch{}return{status:n.status,json:r}}function errorFrom(e,t){const n="string"==typeof e.json.error?e.json.error:"";if(e.status>=500||429===e.status||!n)return new d(`${t} failed (HTTP ${e.status}).`,n||"server",!1);const r="string"==typeof e.json.error_description?` ${e.json.error_description}`:"";return new d(`${t} failed: ${n}.${r}`,n,!0)}async function requestDeviceAuthorization(e){const t=await postForm(`${e.issuer}/oauth/device_authorization`,{client_id:e.clientId,scope:u}),n=t.json;if(200!==t.status||"string"!=typeof n.device_code||"string"!=typeof n.user_code||"string"!=typeof n.verification_uri)throw errorFrom(t,"Starting sign-in");const r="number"==typeof n.expires_in?n.expires_in:600,o="number"==typeof n.interval?n.interval:5;return{deviceCode:n.device_code,userCode:n.user_code,verificationUri:n.verification_uri,verificationUriComplete:"string"==typeof n.verification_uri_complete?n.verification_uri_complete:`${n.verification_uri}?user_code=${encodeURIComponent(n.user_code)}`,expiresAt:Date.now()+1e3*r,intervalMs:1e3*o}}function tokensFrom(e,t){const n=e.json;if(200!==e.status||"string"!=typeof n.access_token)return null;const r="string"==typeof n.refresh_token?n.refresh_token:t;if(!r)return null;const o="number"==typeof n.expires_in?n.expires_in:3600;return{accessToken:n.access_token,refreshToken:r,accessTokenExpiresAt:Date.now()+1e3*o}}async function pollDeviceToken(e,t,n={}){const r=n.sleep??abortableSleep;let o=t.intervalMs;for(;;){if(await r(o,n.signal),n.signal?.aborted)throw new d("Sign-in cancelled.","cancelled",!0);if(Date.now()>=t.expiresAt)throw new d("The sign-in link expired before it was approved.","expired_token",!0);let s;try{s=await postForm(`${e.issuer}/oauth/token`,{grant_type:"urn:ietf:params:oauth:grant-type:device_code",device_code:t.deviceCode,client_id:e.clientId})}catch{continue}const i=tokensFrom(s);if(i)return i;const a="string"==typeof s.json.error?s.json.error:"";if("authorization_pending"===a)continue;if("slow_down"===a){o+=5e3;continue}const c=errorFrom(s,"Sign-in");if(c.terminal){if("access_denied"===a)throw new d("Sign-in was declined.",a,!0);throw c}}}async function refreshOAuthTokens(e,t){const n=await postForm(`${e.issuer}/oauth/token`,{grant_type:"refresh_token",refresh_token:t,client_id:e.clientId}),r=tokensFrom(n,t);if(r)return r;throw errorFrom(n,"Renewing the Tempo sign-in")}async function revokeOAuthToken(e,t){try{const n=await postForm(`${e.issuer}/oauth/token/revoke`,{token:t,token_type_hint:"refresh_token",client_id:e.clientId});return 200===n.status}catch{return!1}}function abortableSleep(e,t){return new Promise(n=>{if(t?.aborted)return n();const r=setTimeout(done,e);function done(){clearTimeout(r),t?.removeEventListener("abort",done),n()}t?.addEventListener("abort",done,{once:!0})})}var h=class extends Error{constructor(e,t){super(e),this.name="SessionExchangeError",this.kind=t}};async function exchangeOAuthForSession(e){let t;try{t=await fetch(`${e.convexSiteUrl}/auth/oauth-session`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({access_token:e.accessToken}),signal:AbortSignal.timeout(3e4)})}catch(e){throw new h(`Couldn't reach Tempo: ${e instanceof Error?e.message:String(e)}`,"transient")}if(401===t.status)throw new h("Tempo refused the sign-in (revoked or not issued to the Tempo MCP).","invalid_token");if(!t.ok)throw new h(`Tempo sign-in returned HTTP ${t.status}.`,"transient");const n=await t.json().catch(()=>({}));if("string"!=typeof n.token||"string"!=typeof n.sessionId||"string"!=typeof n.userId)throw new h("Tempo sign-in returned an incomplete response.","transient");return{token:n.token,sessionId:n.sessionId,userId:n.userId}}var f=3e5;function grantFrom(e,t){return{issuer:e.issuer,clientId:e.clientId,refreshToken:t.refreshToken,accessToken:t.accessToken,accessTokenExpiresAt:t.accessTokenExpiresAt}}function storedFrom(e,t,n){const r=decodeJwtClaims(e.token),o=n?.userId===e.userId;return{token:e.token,sessionId:e.sessionId,userId:e.userId,email:r.email??(o?n?.email:void 0),firstName:o?n?.firstName:void 0,lastName:o?n?.lastName:void 0,lastOrgId:o?n?.lastOrgId??null:null,expiresAt:decodeJwtExp(e.token),oauth:t}}async function completeSignIn(e){const t=await exchangeOAuthForSession({convexSiteUrl:e.convexSiteUrl,accessToken:e.tokens.accessToken});return withAuthLock(async()=>{const n=storedFrom(t,grantFrom(e.config,e.tokens),await readAuth());return await writeAuth(n),n})}async function renewSessionWithOAuth(e){return withAuthLock(async()=>{const t=await readAuth();if(!t)return"signed_out";if(t.sessionId!==e.staleSessionId)return"renewed";const n=t.oauth;if(!n)return await clearAuth(),"signed_out";const r={issuer:n.issuer,clientId:n.clientId};let o=n,s=!1;const refresh=async()=>{let e;try{e=await refreshOAuthTokens(r,o.refreshToken)}catch(e){return e instanceof d&&e.terminal?(await clearAuth(),"signed_out"):"unavailable"}return o=grantFrom(r,e),s=!0,await writeAuth({...t,oauth:o}),null};if(!o.accessToken||(o.accessTokenExpiresAt??0)-Date.now()<f){const e=await refresh();if(e)return e}for(;;)try{const n=await exchangeOAuthForSession({convexSiteUrl:e.convexSiteUrl,accessToken:o.accessToken});return await writeAuth(storedFrom(n,o,t)),"renewed"}catch(e){if(e instanceof h&&"invalid_token"===e.kind){if(s)return await clearAuth(),"signed_out";const e=await refresh();if(e)return e;continue}return"unavailable"}})}function decodeJwtClaims(e){try{const t=JSON.parse(Buffer.from(e.split(".")[1]??"","base64url").toString("utf8"));return"string"==typeof t.email?{email:t.email}:{}}catch{return{}}}function createRefreshLoop(e){const t=e.refreshLeadMs??6e4,n=e.retryDelayMs??5e3,r=e.maxRetries??3;let o=null,s=!1;async function renewOrGiveUp(t){const n=await renewSessionWithOAuth({convexSiteUrl:e.convexSiteUrl,staleSessionId:t}).catch(()=>"unavailable");return"renewed"===n?(await readAuth())?.token??null:("signed_out"===n&&e.onReauthRequired(),null)}async function refreshNow(){const t=await readAuth();if(!t)return e.onReauthRequired(),null;for(let o=0;o<=r;o++)try{const s=await fetch(`${e.convexSiteUrl}/auth/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionId:t.sessionId})});if(401===s.status)return renewOrGiveUp(t.sessionId);if(!s.ok){if(o<r){await sleep(n*Math.pow(1.5,o));continue}return null}const i=await s.json();if(!i.token)return null;const a=i.token;return await withAuthLock(async()=>{const e=await readAuth();if(!e)return null;if(e.sessionId!==t.sessionId)return e.token;const n={...e,token:a,expiresAt:decodeJwtExp(a)};return await writeAuth(n),a})}catch{if(o<r){await sleep(n*Math.pow(1.5,o));continue}return null}return null}function schedule(e){if(o&&clearTimeout(o),s)return;const n=Math.max(0,e.expiresAt-Date.now()-t);o=setTimeout(()=>{refreshNow().then(e=>{e&&!s&&readAuth().then(e=>{e&&schedule(e)})})},n),"function"==typeof o.unref&&o.unref()}function start(){s=!1,readAuth().then(e=>{e&&schedule(e)})}function stop(){s=!0,o&&(clearTimeout(o),o=null)}return{start,stop,refreshNow}}function sleep(e){return new Promise(t=>setTimeout(t,e))}function createAuthProvider(e){return{async getToken(){const t=await readAuth();if(!t)throw new Error("Not signed in to Tempo. Retry the tool to get a sign-in link, or run `npx -y @tempo-ai/mcp login`.");if(t.expiresAt-Date.now()<3e4){const t=await e.refreshNow();if(t){const e=await readAuth();if(e)return{jwt:e.token,expiresAt:e.expiresAt}}throw new Error("Tempo session expired. Retry the tool to get a sign-in link, or run `npx -y @tempo-ai/mcp login`.")}return{jwt:t.token,expiresAt:t.expiresAt}}}}async function startDeviceSignIn(e){const t=e.oauth??resolveOAuthConfig(),n=await requestDeviceAuthorization(t),r=new AbortController,o=(async()=>{const o=await pollDeviceToken(t,n,{signal:r.signal,sleep:e.sleep});await completeSignIn({convexSiteUrl:e.convexSiteUrl,config:t,tokens:o})})();return o.catch(()=>{}),{signInUrl:n.verificationUriComplete,userCode:n.userCode,expiresAt:n.expiresAt,done:o,cancel:()=>r.abort()}}import{exec as p}from"child_process";import{promisify as m}from"util";var w=m(p);function browserLaunchSuppressed(){return"1"===process.env.TEMPO_MCP_NO_BROWSER}async function openInBrowser(e){if(browserLaunchSuppressed())return!1;const t="darwin"===process.platform?`open "${e}"`:"win32"===process.platform?`start "" "${e}"`:`xdg-open "${e}"`;try{return await w(t,{windowsHide:!0}),!0}catch{return!1}}function createSignInPrompt(e){const t=e.openBrowser??openInBrowser,n=e.startSignIn??startDeviceSignIn;let r=null;const isUsable=async e=>{if(!e||e.spent)return!1;try{return(await e.handle).expiresAt>Date.now()+5e3}catch{return!1}},currentOrFresh=async()=>{if(r&&await isUsable(r))return r;r?.handle.then(e=>e.cancel()).catch(()=>{});const t={handle:n(e),browserOpened:null,spent:!1};return t.handle.then(e=>e.done).catch(()=>{}).finally(()=>{t.spent=!0}),r=t,t};return{async ensure(e){for(;;){if(await readAuth())return"signed_in";const n=await currentOrFresh(),r=await n.handle;n.browserOpened||(n.browserOpened=t(r.signInUrl));const o=await n.browserOpened,s=await Promise.race([r.done.then(()=>!0,()=>!1),sleep2(e).then(()=>!1)]);if(!s)return{signInUrl:r.signInUrl,userCode:r.userCode,browserOpened:o};n.spent=!0}},dispose(){r&&!r.spent&&r.handle.then(e=>e.cancel()).catch(()=>{})}}}function sleep2(e){return new Promise(t=>{const n=setTimeout(t,e);"function"==typeof n.unref&&n.unref()})}import{randomUUID as g}from"crypto";import{Server as y}from"@modelcontextprotocol/sdk/server/index.js";import{Client as v}from"@modelcontextprotocol/sdk/client/index.js";import{InMemoryTransport as k}from"@modelcontextprotocol/sdk/inMemory.js";import{CallToolRequestSchema as S,ListResourcesRequestSchema as A,ListToolsRequestSchema as T,ReadResourceRequestSchema as _}from"@modelcontextprotocol/sdk/types.js";var x=5e4;function exceedsElementLimit(e,t){let n=0;const r=[e];for(;r.length>0;){const e=r.pop();if(null===e||"object"!=typeof e)continue;const o=Array.isArray(e)?e:Object.values(e);if(n+=o.length,n>t)return!0;for(const e of o)null!==e&&"object"==typeof e&&r.push(e)}return!1}var I=6e5;async function createAggregateServer(e){const{name:t,version:n,instructions:r,backends:o,filterTool:s,injectParams:i,onScopedCall:a,gateCall:c}=e,u=[];for(const e of o){const[r,o]=k.createLinkedPair(),s=new v({name:`${t}-aggregator`,version:n});await e.server.connect(o),await s.connect(r),u.push({...e,client:s})}const l=new Map,d=new Map,h=new Map;for(const t of u){if(!t.client.getServerCapabilities()?.tools){h.set(t.toolset,[]);continue}const n=await t.client.listTools(),r=[];for(const o of n.tools){const n=e.toolIcons?.[o.name],a=e.toolAnnotations?.[o.name],c={...o,...n?{icons:n}:{},...a?{annotations:{...o.annotations,...a}}:{}};if(s&&!s(t.toolset,c.name))continue;const u=l.get(c.name);if(u)throw new Error(`MCP aggregate tool name collision: "${c.name}" registered by both "${u.toolset}" and "${t.toolset}"`);l.set(c.name,t);const h=i?.(t.toolset,c.name)??[];if(0===h.length){r.push(c);continue}d.set(c.name,h);const f=c.inputSchema??{type:"object"};r.push({...c,inputSchema:{...f,type:"object",properties:{...f.properties??{},...Object.fromEntries(h.map(e=>[e.name,{type:"string",description:e.description}]))},required:[...new Set([...f.required??[],...h.map(e=>e.name)])]}})}h.set(t.toolset,r)}const f=new y({name:t,version:n,...e.icons?{icons:e.icons}:{}},{capabilities:{tools:{},resources:{}},instructions:r});f.setRequestHandler(T,async()=>({tools:u.flatMap(e=>h.get(e.toolset)??[])}));let p=Promise.resolve();f.setRequestHandler(S,async(t,n)=>{const r=t.params.name;if(exceedsElementLimit(t.params.arguments,x))return{isError:!0,content:[{type:"text",text:JSON.stringify({error:{code:"tool_input_too_large",message:`Arguments for "${r}" contain more than ${x} array elements and object members. Split the call into smaller ones.`}})}]};const o=l.get(r);if(!o)return{isError:!0,content:[{type:"text",text:JSON.stringify({error:{code:"unknown_tool",message:`No registered tool named "${r}"`}})}]};const s=performance.now();let i;try{return i=await(async()=>{if(c){const e=await c(o.toolset,r);if(e)return e}const e={...t.params.arguments??{}},s=d.get(r)??[],i={};for(const t of s){const n=e[t.name];if(delete e[t.name],"string"!=typeof n||0===n.length)return{isError:!0,content:[{type:"text",text:JSON.stringify({error:{code:"missing_scope_param",message:`"${r}" requires "${t.name}". ${t.description}`}})}]};i[t.name]=n}const u=p.then(async()=>{n.signal.throwIfAborted(),s.length>0&&a?.(i);const t=g();o.onRequestStart?.(t);try{return await o.client.callTool({name:r,arguments:e},void 0,{timeout:I,signal:o.forwardCancellation?n.signal:void 0})}finally{o.onRequestEnd?.(t)}});return p=u.then(()=>{},()=>{}),await u})(),i}finally{try{e.onToolCallFinished?.({name:r,toolset:o.toolset,args:t.params.arguments??{},result:i,durationMs:Math.round(performance.now()-s)})}catch{}}});const listResourcesForBackend=async e=>{const t=e.client.getServerCapabilities();if(!t?.resources)return[];const n=await e.client.listResources();return n.resources};return f.setRequestHandler(A,async()=>{const e=await Promise.all(u.map(listResourcesForBackend));return{resources:e.flat()}}),f.setRequestHandler(_,async e=>{const t=e.params.uri;for(const e of u){const n=await listResourcesForBackend(e);if(n.some(e=>e.uri===t))return e.client.readResource({uri:t})}throw new Error(`Unknown resource: ${t}`)}),{server:f,connect:e=>f.connect(e),dispose:async()=>{for(const e of u)await e.client.close().catch(()=>{}),e.dispose?.();await f.close().catch(()=>{})}}}import b from"fs";import E from"fs/promises";import O from"path";function installProcessSafety(e={}){const t=e.binaryName??O.basename(process.argv[1]??"tempo-mcp"),logError=(e,n)=>{const r=`[${(new Date).toISOString()}] ${e}: ${n instanceof Error?n.stack||n.message:String(n)}\n`;try{b.mkdirSync(logsDir(),{recursive:!0,mode:448}),b.appendFileSync(logFilePath(t),r,{mode:384})}catch{try{process.stderr.write(r)}catch{}}},onUncaught=e=>logError("uncaughtException",e),onUnhandled=e=>logError("unhandledRejection",e);process.on("uncaughtException",onUncaught),process.on("unhandledRejection",onUnhandled);const stdoutError=e=>{"EPIPE"!==e.code&&logError("stdout-error",e)};process.stdout.on("error",stdoutError);const onSignal=t=>{Promise.resolve(e.onShutdown?.()).catch(e=>logError(`shutdown:${t}`,e)).finally(()=>{setTimeout(()=>process.exit(0),50)})};return process.once("SIGTERM",()=>onSignal("SIGTERM")),process.once("SIGINT",()=>onSignal("SIGINT")),()=>{process.off("uncaughtException",onUncaught),process.off("unhandledRejection",onUnhandled),process.stdout.off("error",stdoutError)}}import{randomUUID as P}from"crypto";import j from"fs";import $ from"path";var C="https://greedy-jackal-526.convex.cloud";function resolveConvexUrl(){return process.env.TEMPO_CONVEX_URL??C}function resolveConvexSiteUrl(e){const t=process.env.TEMPO_CONVEX_SITE_URL;return t||e.replace(/\.convex\.cloud$/,".convex.site")}var M=12e4;function resolveSignInWaitMs(){const e=Number(process.env.TEMPO_MCP_SIGN_IN_WAIT_MS);return Number.isFinite(e)&&e>=0?e:M}var U=["design-context","issues","docs","comments","agents","scripts","slack","linear","canvas"];function parseServeArgs(e){let t=[...U],n="1"===process.env.TEMPO_MCP_READONLY;for(let r=0;r<e.length;r++){const o=e[r];if("--readonly"===o)n=!0;else{if("--toolsets"!==o)return{error:`Unknown flag: ${o}`};{const n=e[++r];if(!n)return{error:"--toolsets requires a comma-separated list"};const o=n.split(",").map(e=>e.trim()).filter(Boolean),s=o.filter(e=>!U.includes(e));if(s.length)return{error:`Unknown toolset(s): ${s.join(", ")}. Valid: ${U.join(", ")}`};t=o}}}return{toolsets:t,readonly:n}}function discoverWorkspace(e=process.cwd()){let t=$.resolve(e);for(;;){const e=$.join(t,"tempo","tempo.config.json");if(j.existsSync(e)){let n="./designs";try{const t=JSON.parse(j.readFileSync(e,"utf8"));t.paths?.canvases&&(n=t.paths.canvases)}catch{}return{workspaceRoot:t,canvasesDir:$.resolve(t,"tempo",n)}}const n=$.dirname(t);if(n===t)return null;t=n}}import{ConvexHttpClient as N}from"convex/browser";var R=class extends Error{constructor(e){super(e.message),this.name="McpToolError",this.error=e}};function mapConvexError(e){const t=e instanceof Error?e.message:String(e);return t.includes("Not authenticated")||t.includes("Unauthenticated")?{code:"auth_required",message:"Authentication required. Please sign in."}:t.includes("not a member")||t.includes("Unauthorized")||t.includes("forbidden")?{code:"forbidden",message:"You are not a member of this organization."}:t.includes("not found")||t.includes("Could not find")?{code:"not_found",message:t}:t.includes("rate limit")||t.includes("Too many requests")?{code:"rate_limited",message:"Rate limited. Please retry after a moment."}:t.includes("Invalid argument")||t.includes("Validator error")?{code:"invalid_args",message:t}:{code:"internal",message:t}}var F=3,D=200,L=class{constructor(e){this.cachedToken=null,this.signal=e.signal;const t=e.fetch??((e,t)=>globalThis.fetch(e,t));this.client=new N(e.url,e.signal||e.fetch?{fetch:e.signal?(n,r)=>t(n,{...r,signal:e.signal}):e.fetch}:void 0),this.authProvider=e.authProvider}async query(e,t){return this.callWithAuth(()=>this.client.query(e,t))}async mutation(e,t){return this.callWithAuth(()=>this.client.mutation(e,t))}async action(e,t){return this.callWithAuth(()=>this.client.action(e,t))}async ensureAuth(e=!1){const t=Date.now();if(!e&&this.cachedToken&&this.cachedToken.expiresAt-t>3e4)return void this.client.setAuth(this.cachedToken.jwt);const n=await this.withSignal(()=>this.authProvider.getToken(e));this.cachedToken=n,this.client.setAuth(n.jwt)}async callWithAuth(e){this.signal?.throwIfAborted(),await this.ensureAuth();for(let t=0;t<F;t++)try{return await this.withSignal(e)}catch(e){this.signal?.throwIfAborted();const n=mapConvexError(e);if("auth_required"===n.code&&0===t){this.cachedToken=null,await this.ensureAuth(!0);continue}if("internal"===n.code&&t<F-1){await this.withSignal(()=>sleep3(D*2**t));continue}throw new R(n)}throw new R({code:"internal",message:"Max retries exceeded"})}withSignal(e){const t=this.signal;return t?(t.throwIfAborted(),new Promise((n,r)=>{const onAbort=()=>r(t.reason);t.addEventListener("abort",onAbort,{once:!0}),Promise.resolve().then(()=>(t.throwIfAborted(),e())).then(n,r).finally(()=>t.removeEventListener("abort",onAbort))})):e()}};function sleep3(e){return new Promise(t=>setTimeout(t,e))}export{R as McpToolError,L as AuthedConvexClient,readAuth,readAuthSync,clearAuth,withAuthLock,revokeOAuthToken,createRefreshLoop,createAuthProvider,startDeviceSignIn,openInBrowser,createSignInPrompt,createAggregateServer,installProcessSafety,resolveConvexUrl,resolveConvexSiteUrl,resolveSignInWaitMs,parseServeArgs,discoverWorkspace};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{createRequire as e}from"node:module";e(import.meta.url);import{NotSignedInError as o,runLogin as n,warnIfLegacyTokenEnv as t}from"./chunk-7NGSCREN.js";import{clearAuth as s,parseServeArgs as r,readAuth as a,resolveConvexSiteUrl as i,resolveConvexUrl as c,revokeOAuthToken as l,withAuthLock as u}from"./chunk-DRKOQGDA.js";var p='tempo-mcp <subcommand>\n\nTempo\'s MCP server — issues, docs, comments, agents, scripts, Slack,\nLinear, and (inside a Tempo repo) canvas tools, served as ONE stdio MCP\nserver.\n\nGet started (no account needed first):\n claude mcp add tempo -- npx -y @tempo-ai/mcp\n Then use any Tempo tool from Claude Code — the first one that needs\n Tempo shows a sign-in link and code (and opens the browser when it can).\n Approve on any device; the sign-in then renews itself. Other hosts\n (Codex / Cursor) take the same command:\n { "tempo": { "command": "npx", "args": ["-y", "@tempo-ai/mcp"] } }\n\nScoping: the AI passes an explicit orgId (and projectId where\nproject-scoped) on every tool call, discovered via the built-in\ntempo_list_orgs / tempo_list_projects tools. Nothing org-related is\nconfigured on the connection.\n\nServer:\n (default) | serve Serve the aggregate MCP server over stdio\n --toolsets a,b Only these toolsets (issues,docs,comments,agents,\n scripts,slack,linear,canvas,design-context). Default: all.\n --readonly Register no write tools at all\n\nDirect tool access (for hosts without MCP support — bot VMs, scripts):\n tools [--schemas] List every tool (add --schemas for arg schemas)\n call <tool> --json \'{"orgId": "..."}\'\n Invoke any tool; same pipeline as the MCP server.\n --json - reads the argument object from stdin.\n Both accept --toolsets / --readonly.\n\nAuth (identity only — optional; the server prompts on first use):\n login Sign in ahead of time: shows a link and code to\n approve on any device (opens the browser if it can)\n logout Sign out of this machine (revokes the sign-in and\n clears ~/.tempo/auth.json)\n whoami Show the signed-in user\n\nEnvironment:\n TEMPO_CONVEX_URL Override the Convex deployment (default: production)\n TEMPO_MCP_READONLY=1 Same as --readonly\n TEMPO_MCP_NO_BROWSER=1 Never open a browser; sign-in links are only\n printed / returned to the host\n TEMPO_MCP_SIGN_IN_WAIT_MS\n How long a tool call waits for the sign-in to be\n approved before returning the link (default 120000)\n';async function runWhoami(){const e=await a();if(!e)return console.log("Not signed in. Use a Tempo tool from your agent to get a sign-in link, or run `npx -y @tempo-ai/mcp login`."),1;const o=e.email?`${e.email} (${e.userId})`:e.userId;console.log(`Signed in as: ${o}`);const n=e.expiresAt-Date.now();return n<=0?console.log(`Token state: expired ${Math.round(-n/1e3)}s ago (refresh on next call)`):console.log(`Token state: fresh, expires in ${Math.round(n/1e3)}s`),console.log(e.oauth?"Renewal: automatic (signed in with OAuth)":"Renewal: none — run `tempo-mcp login` once to switch to automatic renewal"),0}async function runLogout(){const e=await u(async()=>{const e=await a();return e?.oauth&&await l({issuer:e.oauth.issuer,clientId:e.oauth.clientId},e.oauth.refreshToken),e&&await fetch(`${i(c())}/auth/revoke`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e.token}`},body:JSON.stringify({sessionId:e.sessionId}),signal:AbortSignal.timeout(1e4)}).catch(()=>{}),await s(),null!==e});return console.log(e?"Signed out. The next Tempo tool call from your agent will prompt for sign-in (or run `npx -y @tempo-ai/mcp login`).":"Not signed in."),0}async function run(e){const[,,s,...a]=e;if("--help"===s||"-h"===s||"help"===s)return process.stdout.write(p),0;t();try{if(!s||"serve"===s||s.startsWith("--")){const e=s&&"serve"!==s?[s,...a]:a,o=r(e);if("error"in o)return console.error(o.error),process.stderr.write(p),1;const{runServe:n}=await(import("./serve-ITS7X53Y.js"));return await n(o)}switch(s){case"login":return await n();case"logout":return await runLogout();case"whoami":return await runWhoami();case"token":return console.error("`tempo-mcp token` was removed along with personal access tokens. Sign in with `tempo-mcp login` — it shows a link you can approve from any device, and the sign-in renews itself."),1;case"tools":{const{runTools:e}=await(import("./call-35TEN5BZ.js"));return await e(a)}case"call":{const{runCall:e}=await(import("./call-35TEN5BZ.js"));return await e(a)}default:return console.error(`Unknown subcommand: ${s}`),process.stderr.write(p),1}}catch(e){return e instanceof o?(console.error(e.message),1):(console.error(e instanceof Error?e.stack||e.message:String(e)),1)}}export{run};
|