@talajs/mcp 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,55 @@
1
- # Temporary Holding Version
1
+ # @talajs/mcp
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A remote [MCP](https://modelcontextprotocol.io) server for Tala. Merchants add it to Claude as a **custom connector** (or to any MCP client), sign in through Tala, choose a business, and ask:
4
+ - "How many espresso beans do I have?"
5
+ - "How did the milk options sell last month?"
6
+ - "What were yesterday's sales by item?"
7
+
8
+ - **As the person, never more.** Every tool calls Tala's REST API in-process as the signed-in person: the same role and store checks, validation and data as the admin. A connection is bound to one business and to the scopes the person allowed. Removing someone, or disconnecting the app, takes effect on its next request.
9
+ - **Built for Workers.** Stateless Streamable HTTP (protocol 2025-11-25), one database client per request, no Durable Objects.
10
+ - **Read-only for now.** Proposals for menu and stock changes, which people confirm before anything changes, come in a later release.
11
+
12
+ ```ts
13
+ import { createTalaAuth } from '@talajs/auth'
14
+ import { createTalaMcp, talaWellKnown } from '@talajs/mcp'
15
+
16
+ const auth = createTalaAuth<Env>({
17
+ …, // as in @talajs/auth
18
+ oauth: (env) => ({ resource: `${env.PUBLIC_ORIGIN}/tala/mcp`, adminPath: '/admin' }),
19
+ })
20
+
21
+ const mcp = createTalaMcp<Env>({ db, auth })
22
+ app.all('/tala/mcp', (c) => mcp(c.req.raw, c.env, c.executionCtx))
23
+ app.get('/.well-known/*', (c) => talaWellKnown({ auth })(c.req.raw, c.env))
24
+ ```
25
+
26
+ Then, in a Cron Trigger, `cleanupOAuthClients(db)` from `@talajs/auth` removes apps that registered but were never used.
27
+
28
+ See [`docs/mcp.md`](../../docs/mcp.md) for setup, connecting Claude, the tools, and limits.
29
+
30
+ ## Tools
31
+
32
+ | Tool | What it answers |
33
+ |---|---|
34
+ | `get_business_overview` | Stores, currencies, time zones, tax rates, your role. |
35
+ | `list_categories` | Menu categories. |
36
+ | `list_items`, `get_item` | Items, variants, prices; an item's modifier groups and options. |
37
+ | `list_modifier_groups`, `get_modifier_group` | Groups, options, price changes, which items use them. |
38
+ | `list_stock_levels`, `get_stock_level` | Stock by name ("espresso" finds "Espresso beans (Bourbon)") and recent movements. |
39
+ | `sales_summary` | Sales for a date range, by day, item or payment method. |
40
+ | `modifier_usage` | How often each option is chosen per item, and options never chosen. |
41
+ | `list_orders`, `get_order` | Recent orders and tabs. |
42
+
43
+ All need `tala:read` and work for any role; the API still limits people to their own stores.
44
+
45
+ ## Options
46
+
47
+ | Option | |
48
+ |---|---|
49
+ | `db` | The same per-request client factory as `createTalaApp`. |
50
+ | `auth` | Your `createTalaAuth` instance, with `oauth` set. |
51
+ | `events` | The event queue, as for `createTalaApp` (used by write tools later). |
52
+ | `allowedOrigins` | Browser origins allowed to call the server. Claude calls server to server and needs none. |
53
+ | `rateLimitPerGrant` | Requests a minute per connection. Default 60. |
54
+ | `rateLimitPerBusiness` | Requests a minute per business. Default 300. |
55
+ | `tools` | Replace or extend the tool list (see `@talajs/mcp/tools`). |
@@ -0,0 +1,4 @@
1
+ export { createTalaMcp, type TalaMcpOptions } from './server.js';
2
+ export * from './tools/index.js';
3
+ export { protectedResourceMetadataUrl, talaWellKnown } from './well-known.js';
4
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,KAAK,cAAc,EAAE,MAAM,aAAa,CAAA;AAChE,cAAc,kBAAkB,CAAA;AAChC,OAAO,EAAE,4BAA4B,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAA"}
package/dist/index.js ADDED
@@ -0,0 +1,4 @@
1
+ export { createTalaMcp } from './server.js';
2
+ export * from './tools/index.js';
3
+ export { protectedResourceMetadataUrl, talaWellKnown } from './well-known.js';
4
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAuB,MAAM,aAAa,CAAA;AAChE,cAAc,kBAAkB,CAAA;AAChC,OAAO,EAAE,4BAA4B,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAA"}
@@ -0,0 +1,35 @@
1
+ import { type Configurable, type EventQueue } from '@talajs/api';
2
+ import { type TalaAuth } from '@talajs/auth';
3
+ import type { TalaDb } from '@talajs/db';
4
+ import { type TalaTool } from './tools/types.js';
5
+ export interface TalaMcpOptions<E> {
6
+ /** The same per-request client factory as `createTalaApp`. */
7
+ db: (env: E) => TalaDb;
8
+ /** The `createTalaAuth` instance, with `oauth` configured. */
9
+ auth: TalaAuth<E>;
10
+ /** Domain events from writes, as for `createTalaApp`. */
11
+ events?: {
12
+ queue: Configurable<EventQueue, E>;
13
+ };
14
+ /** Browser origins allowed to call the server (Claude calls from its servers and needs none). */
15
+ allowedOrigins?: string[];
16
+ /** Requests a minute per connection (person, client and business). Default 60. */
17
+ rateLimitPerGrant?: number;
18
+ /** Requests a minute per business, across every connection. Default 300. */
19
+ rateLimitPerBusiness?: number;
20
+ /** Replace or extend the tool list. */
21
+ tools?: readonly TalaTool[];
22
+ }
23
+ interface Ctx {
24
+ waitUntil(promise: Promise<unknown>): void;
25
+ }
26
+ /**
27
+ * A remote MCP server (Streamable HTTP, stateless) for Tala. Mount it at the URL you configured
28
+ * as `oauth.resource` in `createTalaAuth`:
29
+ *
30
+ * const mcp = createTalaMcp({ db, auth })
31
+ * app.all('/tala/mcp', (c) => mcp(c.req.raw, c.env, c.executionCtx))
32
+ */
33
+ export declare function createTalaMcp<E>(options: TalaMcpOptions<E>): (request: Request, env: E, ctx?: Ctx) => Promise<Response>;
34
+ export {};
35
+ //# sourceMappingURL=server.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"server.d.ts","sourceRoot":"","sources":["../src/server.ts"],"names":[],"mappings":"AAGA,OAAO,EAEL,KAAK,YAAY,EAGjB,KAAK,UAAU,EAGhB,MAAM,aAAa,CAAA;AACpB,OAAO,EAAsD,KAAK,QAAQ,EAAE,MAAM,cAAc,CAAA;AAEhG,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,YAAY,CAAA;AAExC,OAAO,EAGL,KAAK,QAAQ,EAId,MAAM,kBAAkB,CAAA;AAGzB,MAAM,WAAW,cAAc,CAAC,CAAC;IAC/B,8DAA8D;IAC9D,EAAE,EAAE,CAAC,GAAG,EAAE,CAAC,KAAK,MAAM,CAAA;IACtB,8DAA8D;IAC9D,IAAI,EAAE,QAAQ,CAAC,CAAC,CAAC,CAAA;IACjB,yDAAyD;IACzD,MAAM,CAAC,EAAE;QAAE,KAAK,EAAE,YAAY,CAAC,UAAU,EAAE,CAAC,CAAC,CAAA;KAAE,CAAA;IAC/C,iGAAiG;IACjG,cAAc,CAAC,EAAE,MAAM,EAAE,CAAA;IACzB,kFAAkF;IAClF,iBAAiB,CAAC,EAAE,MAAM,CAAA;IAC1B,4EAA4E;IAC5E,oBAAoB,CAAC,EAAE,MAAM,CAAA;IAC7B,uCAAuC;IACvC,KAAK,CAAC,EAAE,SAAS,QAAQ,EAAE,CAAA;CAC5B;AAMD,UAAU,GAAG;IACX,SAAS,CAAC,OAAO,EAAE,OAAO,CAAC,OAAO,CAAC,GAAG,IAAI,CAAA;CAC3C;AA2BD;;;;;;GAMG;AACH,wBAAgB,aAAa,CAAC,CAAC,EAAE,OAAO,EAAE,cAAc,CAAC,CAAC,CAAC,aAmBnB,OAAO,OAAO,CAAC,QAAQ,GAAG,KAAG,OAAO,CAAC,QAAQ,CAAC,CAyFrF"}
package/dist/server.js ADDED
@@ -0,0 +1,222 @@
1
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
2
+ import { WebStandardStreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js';
3
+ import { CfWorkerJsonSchemaValidator } from '@modelcontextprotocol/sdk/validation/cfworker-provider.js';
4
+ import { consumeRateLimit, createTalaApp, } from '@talajs/api';
5
+ import { OAUTH_SCOPES, resolveAccessToken } from '@talajs/auth';
6
+ import { talaTools } from './tools/index.js';
7
+ import { ToolError, toolsFor, } from './tools/types.js';
8
+ import { protectedResourceMetadataUrl } from './well-known.js';
9
+ const VERSION = '0.2.0';
10
+ /** Results larger than this are cut, and the model is told to page or narrow the query. */
11
+ const MAX_RESULT_CHARS = 50_000;
12
+ /** Per-request data for the internal API app, carried on a private env wrapper. */
13
+ const REQUEST = Symbol('tala-mcp-request');
14
+ function challenge(resource, status, error) {
15
+ const parts = [
16
+ `resource_metadata="${protectedResourceMetadataUrl(resource)}"`,
17
+ `scope="${OAUTH_SCOPES.join(' ')}"`,
18
+ ];
19
+ if (error)
20
+ parts.unshift(`error="${error}"`);
21
+ return new Response(JSON.stringify({ error: error ?? 'unauthorized' }), {
22
+ status,
23
+ headers: {
24
+ 'content-type': 'application/json',
25
+ 'www-authenticate': `Bearer ${parts.join(', ')}`,
26
+ },
27
+ });
28
+ }
29
+ const jsonRpcError = (status, message, headers = {}) => new Response(JSON.stringify({ jsonrpc: '2.0', error: { code: -32000, message }, id: null }), {
30
+ status,
31
+ headers: { 'content-type': 'application/json', ...headers },
32
+ });
33
+ /**
34
+ * A remote MCP server (Streamable HTTP, stateless) for Tala. Mount it at the URL you configured
35
+ * as `oauth.resource` in `createTalaAuth`:
36
+ *
37
+ * const mcp = createTalaMcp({ db, auth })
38
+ * app.all('/tala/mcp', (c) => mcp(c.req.raw, c.env, c.executionCtx))
39
+ */
40
+ export function createTalaMcp(options) {
41
+ const tools = options.tools ?? talaTools;
42
+ // The REST API, called in-process as the person: the same validation, role and store checks
43
+ // and response shapes as the admin, with nothing duplicated.
44
+ const internalAuth = {
45
+ name: 'mcp',
46
+ authenticate: async (c) => c.env[REQUEST].identity,
47
+ };
48
+ const api = createTalaApp({
49
+ // The request's own client; the MCP handler disposes of it once.
50
+ db: (env) => ({ ...env[REQUEST].db, dispose: async () => { } }),
51
+ auth: internalAuth,
52
+ ...(options.events
53
+ ? { events: options.events }
54
+ : {}),
55
+ openapi: false,
56
+ });
57
+ return async function handle(request, env, ctx) {
58
+ const settings = options.auth.oauth(env);
59
+ if (!settings)
60
+ throw new Error('createTalaMcp: configure `oauth` in createTalaAuth');
61
+ const resource = settings.resource;
62
+ if (request.method !== 'POST') {
63
+ return new Response(null, { status: 405, headers: { allow: 'POST' } });
64
+ }
65
+ // Browsers send Origin; reject unknown ones (DNS rebinding). Server-to-server calls have none.
66
+ const origin = request.headers.get('origin');
67
+ if (origin &&
68
+ origin !== new URL(resource).origin &&
69
+ !options.allowedOrigins?.includes(origin)) {
70
+ return jsonRpcError(403, 'Origin not allowed');
71
+ }
72
+ const bearer = /^Bearer\s+(\S+)$/i.exec(request.headers.get('authorization') ?? '')?.[1];
73
+ if (!bearer)
74
+ return challenge(resource, 401);
75
+ const db = options.db(env);
76
+ try {
77
+ const access = await resolveAccessToken(db, bearer, resource);
78
+ if (!access)
79
+ return challenge(resource, 401, 'invalid_token');
80
+ const membership = await db.client.membership.findUnique({
81
+ where: { tenantId_subject: { tenantId: access.tenantId, subject: access.subject } },
82
+ include: { tenant: { select: { name: true, defaultCurrency: true, disabledAt: true } } },
83
+ });
84
+ // Removed from the business (or the business disabled): the grant is worthless.
85
+ if (!membership || membership.revokedAt || membership.tenant.disabledAt) {
86
+ return challenge(resource, 401, 'invalid_token');
87
+ }
88
+ const grantLimit = { window: 60, max: options.rateLimitPerGrant ?? 60 };
89
+ const businessLimit = { window: 60, max: options.rateLimitPerBusiness ?? 300 };
90
+ for (const [key, rule] of [
91
+ [`mcp:grant:${access.clientId}:${access.userId}:${access.tenantId}`, grantLimit],
92
+ [`mcp:tenant:${access.tenantId}`, businessLimit],
93
+ ]) {
94
+ const limit = await consumeRateLimit(db, key, rule);
95
+ if (!limit.allowed) {
96
+ return jsonRpcError(429, 'Too many requests; slow down', {
97
+ 'retry-after': String(limit.retryAfter),
98
+ });
99
+ }
100
+ }
101
+ const identity = {
102
+ kind: 'staff',
103
+ subject: access.subject,
104
+ email: access.email,
105
+ emailVerified: access.emailVerified,
106
+ ...(access.name ? { name: access.name } : {}),
107
+ tenantId: access.tenantId,
108
+ scopes: access.scopes,
109
+ claims: { oauthClientId: access.clientId },
110
+ };
111
+ const internalEnv = Object.assign(Object.create(env), {
112
+ [REQUEST]: { db, identity },
113
+ });
114
+ const toolCtx = await toolContext(api, internalEnv, access, membership.role, {
115
+ name: membership.tenant.name,
116
+ currency: membership.tenant.defaultCurrency,
117
+ });
118
+ const server = new McpServer({ name: 'tala', title: membership.tenant.name, version: VERSION }, {
119
+ jsonSchemaValidator: new CfWorkerJsonSchemaValidator(),
120
+ instructions: 'Tala runs this business: menu, stock, orders and sales. Call get_business_overview first for store ids and time zones. Money comes as exact minor units plus a formatted string; times are in the store time zone.',
121
+ });
122
+ for (const tool of toolsFor(tools, membership.role, access.scopes))
123
+ register(server, tool, toolCtx);
124
+ const transport = new WebStandardStreamableHTTPServerTransport({
125
+ sessionIdGenerator: undefined,
126
+ enableJsonResponse: true,
127
+ });
128
+ await server.connect(transport);
129
+ return await transport.handleRequest(request);
130
+ }
131
+ finally {
132
+ const done = db.dispose();
133
+ if (ctx)
134
+ ctx.waitUntil(done);
135
+ else
136
+ await done;
137
+ }
138
+ };
139
+ }
140
+ function register(server, tool, ctx) {
141
+ server.registerTool(tool.name, {
142
+ title: tool.title,
143
+ description: tool.description,
144
+ inputSchema: tool.input.shape,
145
+ annotations: {
146
+ title: tool.title,
147
+ readOnlyHint: tool.readOnly,
148
+ destructiveHint: tool.destructive ?? false,
149
+ openWorldHint: false,
150
+ },
151
+ }, async (input) => {
152
+ try {
153
+ const result = await tool.run(ctx, tool.input.parse(input));
154
+ let text = JSON.stringify(result);
155
+ if (text.length > MAX_RESULT_CHARS) {
156
+ text = JSON.stringify({
157
+ error: 'result_too_large',
158
+ message: 'The result is too large. Narrow the query (q, dates, store) or use a smaller limit and page with nextCursor.',
159
+ });
160
+ return { content: [{ type: 'text', text }], isError: true };
161
+ }
162
+ return {
163
+ content: [{ type: 'text', text }],
164
+ structuredContent: result,
165
+ };
166
+ }
167
+ catch (error) {
168
+ const e = error instanceof ToolError
169
+ ? error
170
+ : new ToolError('internal_error', 'Internal error', 500);
171
+ if (!(error instanceof ToolError))
172
+ console.error('tala-mcp: tool failed', tool.name, error);
173
+ return {
174
+ content: [
175
+ { type: 'text', text: JSON.stringify({ error: e.code, message: e.message }) },
176
+ ],
177
+ isError: true,
178
+ };
179
+ }
180
+ });
181
+ }
182
+ async function toolContext(api, env, access, role, tenant) {
183
+ const base = `/v1/tenants/${access.tenantId}`;
184
+ async function call(method, path, body, query) {
185
+ const url = new URL(`http://tala.internal${base}${path}`);
186
+ for (const [k, v] of Object.entries(query ?? {})) {
187
+ if (v !== undefined && v !== null && v !== '')
188
+ url.searchParams.set(k, String(v));
189
+ }
190
+ const res = await api.request(url.pathname + url.search, {
191
+ method,
192
+ ...(body === undefined
193
+ ? {}
194
+ : { body: JSON.stringify(body), headers: { 'content-type': 'application/json' } }),
195
+ }, env);
196
+ const text = await res.text();
197
+ const json = text ? JSON.parse(text) : null;
198
+ if (!res.ok) {
199
+ throw new ToolError(json?.error?.code ?? 'error', json?.error?.message ?? res.statusText, res.status);
200
+ }
201
+ return json;
202
+ }
203
+ const stores = await call('GET', '/stores', undefined, { limit: 200 });
204
+ return {
205
+ tenantId: access.tenantId,
206
+ tenantName: tenant.name,
207
+ currency: tenant.currency,
208
+ role,
209
+ scopes: access.scopes,
210
+ stores: stores.data.map(({ id, name, currency, timezone }) => ({
211
+ id,
212
+ name,
213
+ currency,
214
+ timezone,
215
+ })),
216
+ get: (path, query) => call('GET', path, undefined, query),
217
+ post: (path, body) => call('POST', path, body ?? {}),
218
+ patch: (path, body) => call('PATCH', path, body),
219
+ del: (path) => call('DELETE', path),
220
+ };
221
+ }
222
+ //# sourceMappingURL=server.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"server.js","sourceRoot":"","sources":["../src/server.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,yCAAyC,CAAA;AACnE,OAAO,EAAE,wCAAwC,EAAE,MAAM,+DAA+D,CAAA;AACxH,OAAO,EAAE,2BAA2B,EAAE,MAAM,2DAA2D,CAAA;AACvG,OAAO,EAGL,gBAAgB,EAChB,aAAa,GAId,MAAM,aAAa,CAAA;AACpB,OAAO,EAAE,YAAY,EAAoB,kBAAkB,EAAiB,MAAM,cAAc,CAAA;AAGhG,OAAO,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAA;AAC5C,OAAO,EAKL,SAAS,EACT,QAAQ,GACT,MAAM,kBAAkB,CAAA;AACzB,OAAO,EAAE,4BAA4B,EAAE,MAAM,iBAAiB,CAAA;AAmB9D,MAAM,OAAO,GAAG,OAAO,CAAA;AACvB,2FAA2F;AAC3F,MAAM,gBAAgB,GAAG,MAAM,CAAA;AAM/B,mFAAmF;AACnF,MAAM,OAAO,GAAG,MAAM,CAAC,kBAAkB,CAAC,CAAA;AAG1C,SAAS,SAAS,CAAC,QAAgB,EAAE,MAAiB,EAAE,KAAc;IACpE,MAAM,KAAK,GAAG;QACZ,sBAAsB,4BAA4B,CAAC,QAAQ,CAAC,GAAG;QAC/D,UAAU,YAAY,CAAC,IAAI,CAAC,GAAG,CAAC,GAAG;KACpC,CAAA;IACD,IAAI,KAAK;QAAE,KAAK,CAAC,OAAO,CAAC,UAAU,KAAK,GAAG,CAAC,CAAA;IAC5C,OAAO,IAAI,QAAQ,CAAC,IAAI,CAAC,SAAS,CAAC,EAAE,KAAK,EAAE,KAAK,IAAI,cAAc,EAAE,CAAC,EAAE;QACtE,MAAM;QACN,OAAO,EAAE;YACP,cAAc,EAAE,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,EAAE,EAAE,KAAK,EAAE,GAAG,EAAE,CAAC,CAAA;IAC7F,OAAO;QACL,QAAQ,EAAE,MAAM,CAAC,QAAQ;QACzB,UAAU,EAAE,MAAM,CAAC,IAAI;QACvB,QAAQ,EAAE,MAAM,CAAC,QAAQ;QACzB,IAAI;QACJ,MAAM,EAAE,MAAM,CAAC,MAAM;QACrB,MAAM,EAAE,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE,QAAQ,EAAE,EAAE,EAAE,CAAC,CAAC;YAC7D,EAAE;YACF,IAAI;YACJ,QAAQ;YACR,QAAQ;SACT,CAAC,CAAC;QACH,GAAG,EAAE,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE,CAAC,IAAI,CAAC,KAAK,EAAE,IAAI,EAAE,SAAS,EAAE,KAAK,CAAC;QACzD,IAAI,EAAE,CAAC,IAAI,EAAE,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,MAAM,EAAE,IAAI,EAAE,IAAI,IAAI,EAAE,CAAC;QACpD,KAAK,EAAE,CAAC,IAAI,EAAE,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,OAAO,EAAE,IAAI,EAAE,IAAI,CAAC;QAChD,GAAG,EAAE,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,QAAQ,EAAE,IAAI,CAAC;KACpC,CAAA;AACH,CAAC"}
@@ -0,0 +1,10 @@
1
+ /** Money for a model: exact minor units plus how a person would write it. */
2
+ export declare const money: (minor: number, currency: string) => {
3
+ minor: number;
4
+ formatted: string;
5
+ };
6
+ /** An instant as local time in the store's time zone, with the offset, e.g. `2026-11-29 08:15 -05:00`. */
7
+ export declare function localTime(iso: string | null | undefined, timezone: string): string | null;
8
+ /** Today's date in a time zone, `YYYY-MM-DD`. */
9
+ export declare const today: (timezone: string) => string;
10
+ //# sourceMappingURL=format.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"format.d.ts","sourceRoot":"","sources":["../../src/tools/format.ts"],"names":[],"mappings":"AAEA,6EAA6E;AAC7E,eAAO,MAAM,KAAK,UAAW,MAAM,YAAY,MAAM;;;CAGnD,CAAA;AAEF,0GAA0G;AAC1G,wBAAgB,SAAS,CAAC,GAAG,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,EAAE,QAAQ,EAAE,MAAM,iBAmBzE;AAED,iDAAiD;AACjD,eAAO,MAAM,KAAK,aAAc,MAAM,WACuC,CAAA"}
@@ -0,0 +1,29 @@
1
+ import { formatMoney } from '@talajs/contracts';
2
+ /** Money for a model: exact minor units plus how a person would write it. */
3
+ export const money = (minor, currency) => ({
4
+ minor,
5
+ formatted: formatMoney(minor, currency),
6
+ });
7
+ /** An instant as local time in the store's time zone, with the offset, e.g. `2026-11-29 08:15 -05:00`. */
8
+ export function localTime(iso, timezone) {
9
+ if (!iso)
10
+ return null;
11
+ const date = new Date(iso);
12
+ const parts = Object.fromEntries(new Intl.DateTimeFormat('en-CA', {
13
+ timeZone: timezone,
14
+ year: 'numeric',
15
+ month: '2-digit',
16
+ day: '2-digit',
17
+ hour: '2-digit',
18
+ minute: '2-digit',
19
+ hourCycle: 'h23',
20
+ timeZoneName: 'longOffset',
21
+ })
22
+ .formatToParts(date)
23
+ .map((p) => [p.type, p.value]));
24
+ const offset = (parts.timeZoneName ?? 'GMT').replace('GMT', '') || '+00:00';
25
+ return `${parts.year}-${parts.month}-${parts.day} ${parts.hour}:${parts.minute} ${offset}`;
26
+ }
27
+ /** Today's date in a time zone, `YYYY-MM-DD`. */
28
+ export const today = (timezone) => new Intl.DateTimeFormat('en-CA', { timeZone: timezone }).format(new Date());
29
+ //# sourceMappingURL=format.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"format.js","sourceRoot":"","sources":["../../src/tools/format.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAA;AAE/C,6EAA6E;AAC7E,MAAM,CAAC,MAAM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,MAAM,CAAC,IAAI,IAAI,EAAE,CAAC,CAAA"}
@@ -0,0 +1,6 @@
1
+ export { localTime, money, today } from './format.js';
2
+ export { readTools } from './read.js';
3
+ export { defineTool, type Query, READ, type Scope, type StoreInfo, type TalaTool, type ToolContext, ToolError, toolsFor, WRITE, } from './types.js';
4
+ /** Every tool Tala ships. */
5
+ export declare const talaTools: import("./types.js").TalaTool<import("zod").ZodObject<import("zod/v4/core").$ZodLooseShape, import("zod/v4/core").$strip>>[];
6
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/tools/index.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,SAAS,EAAE,KAAK,EAAE,KAAK,EAAE,MAAM,aAAa,CAAA;AACrD,OAAO,EAAE,SAAS,EAAE,MAAM,WAAW,CAAA;AACrC,OAAO,EACL,UAAU,EACV,KAAK,KAAK,EACV,IAAI,EACJ,KAAK,KAAK,EACV,KAAK,SAAS,EACd,KAAK,QAAQ,EACb,KAAK,WAAW,EAChB,SAAS,EACT,QAAQ,EACR,KAAK,GACN,MAAM,YAAY,CAAA;AAEnB,6BAA6B;AAC7B,eAAO,MAAM,SAAS,8HAAiB,CAAA"}
@@ -0,0 +1,7 @@
1
+ import { readTools } from './read.js';
2
+ export { localTime, money, today } from './format.js';
3
+ export { readTools } from './read.js';
4
+ export { defineTool, READ, ToolError, toolsFor, WRITE, } from './types.js';
5
+ /** Every tool Tala ships. */
6
+ export const talaTools = [...readTools];
7
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/tools/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,WAAW,CAAA;AAErC,OAAO,EAAE,SAAS,EAAE,KAAK,EAAE,KAAK,EAAE,MAAM,aAAa,CAAA;AACrD,OAAO,EAAE,SAAS,EAAE,MAAM,WAAW,CAAA;AACrC,OAAO,EACL,UAAU,EAEV,IAAI,EAKJ,SAAS,EACT,QAAQ,EACR,KAAK,GACN,MAAM,YAAY,CAAA;AAEnB,6BAA6B;AAC7B,MAAM,CAAC,MAAM,SAAS,GAAG,CAAC,GAAG,SAAS,CAAC,CAAA"}
@@ -0,0 +1,3 @@
1
+ import { z } from 'zod';
2
+ export declare const readTools: import("./types.js").TalaTool<z.ZodObject<z.core.$ZodLooseShape, z.core.$strip>>[];
3
+ //# sourceMappingURL=read.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"read.d.ts","sourceRoot":"","sources":["../../src/tools/read.ts"],"names":[],"mappings":"AAaA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAA;AA4DvB,eAAO,MAAM,SAAS,oFAkVrB,CAAA"}