Skip to content
Back to search

mcp-boilerplate

A remote Cloudflare MCP server boilerplate with user authentication and Stripe for paid tools.

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today
Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/iannuttall--mcp-boilerplate/badge.svg)](/listings/iannuttall--mcp-boilerplate)

HTML

<a href="/listings/iannuttall--mcp-boilerplate"><img src="/api/listings/iannuttall--mcp-boilerplate/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

Step 1: Get the Code

1. Clone this repository to your computer:

git clone https://github.com/iannuttall/mcp-boilerplate.git
cd mcp-boilerplate

2. Install everything needed:

npm install

Step 2: Set Up the Database

1. Install Wrangler (Cloudflare's tool) if you haven't already:

npm install -g wrangler

2. Create a database for user login:

npx wrangler kv namespace create "OAUTH_KV"

Note: you can't use a different name for this database. It has to be "OAUTH_KV".

3. After running this command, you'll see some text that includes `id` and `preview_id` values

4. Open the `wrangler.jsonc` file in the project folder

5. Look for the section with `"kv_namespaces": [`

6. Add your database information there:

"kv_namespaces": [
  {
    "binding": "OAUTH_KV",
    "id": "paste-your-id-here",
    "preview_id": "paste-your-preview-id-here"
  }
]

Step 3: Set Up Your Local Settings

1. Create a file for your settings:

cp .dev.vars.example .dev.vars

2. Open the `.dev.vars` file in your code editor

3. You'll need to add several values here (we'll get them in the next steps)

Step 4a: Setting Up Google Login (Recommended)

1. Go to the [Google Cloud Console](https://console.cloud.google.com/) 2. Create a new project with any name you like 3. Go to "APIs & Services" > "Credentials" 4. Click "+ CREATE CREDENTIALS" and choose "OAuth client ID" 5. If prompted, set up a consent screen: - Choose "External" for User Type - Add an App name (like "My AI Tool") - Add your email address where required - You can skip the "Scopes" and "Test users" sections 6. For the OAuth client: - Select "Web application" for Application type - Give it a name - Under "Authorized redirect URIs" add the following:

http://localhost:8787/callback/google

7. Click "CREATE" 8. You'll now see your Client ID and Client Secret - copy these values 9. Add them to your `.dev.vars` file:

GOOGLE_CLIENT_ID="paste-your-client-id-here"
GOOGLE_CLIENT_SECRET="paste-your-client-secret-here"

Once you've completed this step, you can proceed directly to Step 5 if you don't need GitHub login.

Step 4b: Setting Up GitHub Login (Optional)

If you prefer to use GitHub for login instead of Google:

1. Go to your GitHub account 2. Click on your profile picture in the top-right corner, then go to "Settings" 3. In the left sidebar, scroll down and click on "Developer settings" 4. Click on "OAuth Apps", then click the "New OAuth App" button 5. Fill in the form: - Application name: Give it a name (like "My AI Tool") - Homepage URL: `http://localhost:8787` - Application description: A brief description of your app (optional) - Authorization callback URL: `http://localhost:8787/callback/github` 6. Click "Register application" 7. On the next page, you'll see your Client ID 8. Click "Generate a new client secret" 9. Copy your Client Secret immediately (you won't be able to see it again) 10. Add these values to your `.dev.vars` file:

GITHUB_CLIENT_ID="paste-your-client-id-here"
GITHUB_CLIENT_SECRET="paste-your-client-secret-here"

11. You'll also need to update the default authentication in your code: - Open `src/index.ts` - Find the import for Google handler: `import { GoogleHandler } from "./auth/google-handler";` - Replace it with: `import { GitHubHandler } from "./auth/github-handler";` - Find the line with `defaultHandler: GoogleHandler as any,` - Change it to: `defaultHandler: GitHubHandler as any,`

After completing either Step 4a or 4b, proceed to Step 5.

Step 5: Setting Up Stripe Payments

1. Log in to your [Stripe Dashboard](https://dashboard.stripe.com/) 2. Get your test API key: - Go to Developers > API keys - Copy your "Secret key" (it starts with `sk_test_`) 3. Create a product and price: - Go to Products > Add Product - Give it a name and description - Add a price (this is what users will pay)

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

README.md · README · 664 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

  1. # MCP Boilerplate: Simple Setup Guide
  2. This project helps you create your own remote MCP server on Cloudflare with user login and payment options. You don't need to be a technical expert to get it running.
  3. > [!NOTE]
  4. > This project is now free to use and open source. If you want to support me, just follow me on X [@iannuttall](https://x.com/iannuttall) and subscribe to [my newsletter](https://ian.is).
  5. ## What You'll Get
  6. - An MCP server that works with Cursor, Claude and other AI assistants
  7. - User login with Google or GitHub
  8. - Payment processing with Stripe
  9. - The ability to create both free and paid MCP tools
  10. ## Setup Checklist
  11. Before starting, make sure you have:
  12. - Node.js installed (download from [nodejs.org](https://nodejs.org/))
  13. - A Cloudflare account (sign up at [dash.cloudflare.com/sign-up](https://dash.cloudflare.com/sign-up))
  14. - A Google account for setting up login (or GitHub if you prefer)
  15. - A Stripe account for payments (sign up at [dashboard.stripe.com/register](https://dashboard.stripe.com/register))
  16. ## Step-by-Step Setup
  17. ### Step 1: Get the Code
  18. 1. Clone this repository to your computer:
  19. ```bash
  20. git clone https://github.com/iannuttall/mcp-boilerplate.git
  21. cd mcp-boilerplate
  22. ```
  23. 2. Install everything needed:
  24. ```bash
  25. npm install
  26. ```
  27. ### Step 2: Set Up the Database
  28. 1. Install Wrangler (Cloudflare's tool) if you haven't already:
  29. ```bash
  30. npm install -g wrangler
  31. ```
  32. 2. Create a database for user login:
  33. ```bash
  34. npx wrangler kv namespace create "OAUTH_KV"
  35. ```
  36. Note: you can't use a different name for this database. It has to be "OAUTH_KV".
  37. 3. After running this command, you'll see some text that includes `id` and `preview_id` values
  38. 4. Open the `wrangler.jsonc` file in the project folder
  39. 5. Look for the section with `"kv_namespaces": [`
  40. 6. Add your database information there:
  41. ```json
  42. "kv_namespaces": [
  43. {
  44. "binding": "OAUTH_KV",
  45. "id": "paste-your-id-here",
  46. "preview_id": "paste-your-preview-id-here"
  47. }
  48. ]
  49. ```
  50. ### Step 3: Set Up Your Local Settings
  51. 1. Create a file for your settings:
  52. ```bash
  53. cp .dev.vars.example .dev.vars
  54. ```
  55. 2. Open the `.dev.vars` file in your code editor
  56. 3. You'll need to add several values here (we'll get them in the next steps)
  57. ### Step 4a: Setting Up Google Login (Recommended)
  58. 1. Go to the [Google Cloud Console](https://console.cloud.google.com/)
  59. 2. Create a new project with any name you like
  60. 3. Go to "APIs & Services" > "Credentials"
  61. 4. Click "+ CREATE CREDENTIALS" and choose "OAuth client ID"
  62. 5. If prompted, set up a consent screen:
  63. - Choose "External" for User Type
  64. - Add an App name (like "My AI Tool")
  65. - Add your email address where required
  66. - You can skip the "Scopes" and "Test users" sections
  67. 6. For the OAuth client:
  68. - Select "Web application" for Application type
  69. - Give it a name
  70. - Under "Authorized redirect URIs" add the following:
  71. ```
  72. http://localhost:8787/callback/google
  73. ```
  74. 7. Click "CREATE"
  75. 8. You'll now see your Client ID and Client Secret - copy these values
  76. 9. Add them to your `.dev.vars` file:
  77. ```ini
  78. GOOGLE_CLIENT_ID="paste-your-client-id-here"
  79. GOOGLE_CLIENT_SECRET="paste-your-client-secret-here"
  80. ```
  81. Once you've completed this step, you can proceed directly to Step 5 if you don't need GitHub login.
  82. ### Step 4b: Setting Up GitHub Login (Optional)
  83. If you prefer to use GitHub for login instead of Google:
  84. 1. Go to your GitHub account
  85. 2. Click on your profile picture in the top-right corner, then go to "Settings"
  86. 3. In the left sidebar, scroll down and click on "Developer settings"
  87. 4. Click on "OAuth Apps", then click the "New OAuth App" button
  88. 5. Fill in the form:
  89. - Application name: Give it a name (like "My AI Tool")
  90. - Homepage URL: `http://localhost:8787`
  91. - Application description: A brief description of your app (optional)
  92. - Authorization callback URL: `http://localhost:8787/callback/github`
  93. 6. Click "Register application"
  94. 7. On the next page, you'll see your Client ID
  95. 8. Click "Generate a new client secret"
  96. 9. Copy your Client Secret immediately (you won't be able to see it again)
  97. 10. Add these values to your `.dev.vars` file:
  98. ```ini
  99. GITHUB_CLIENT_ID="paste-your-client-id-here"
  100. GITHUB_CLIENT_SECRET="paste-your-client-secret-here"
  101. ```
  102. 11. You'll also need to update the default authentication in your code:
  103. - Open `src/index.ts`
  104. - Find the import for Google handler: `import { GoogleHandler } from "./auth/google-handler";`
  105. - Replace it with: `import { GitHubHandler } from "./auth/github-handler";`
  106. - Find the line with `defaultHandler: GoogleHandler as any,`
  107. - Change it to: `defaultHandler: GitHubHandler as any,`
  108. After completing either Step 4a or 4b, proceed to Step 5.
  109. ### Step 5: Setting Up Stripe Payments
  110. 1. Log in to your [Stripe Dashboard](https://dashboard.stripe.com/)
  111. 2. Get your test API key:
  112. - Go to Developers > API keys
  113. - Copy your "Secret key" (it starts with `sk_test_`)
  114. 3. Create a product and price:
  115. - Go to Products > Add Product
  116. - Give it a name and description
  117. - Add a price (this is what users will pay)
  118. - Save the product
  119. - After saving, find and copy the "Price ID" (it starts with `price_`)
  120. 4. Add these values to your `.dev.vars` file:
  121. ```ini
  122. STRIPE_SECRET_KEY="sk_test_your-key-here"
  123. STRIPE_SUBSCRIPTION_PRICE_ID="price_your-price-id-here"
  124. STRIPE_METERED_PRICE_ID="your-stripe-metered-price-id"
  125. ```
  126. ### Step 5a: Configuring the Stripe Customer Billing Portal
  127. This boilerplate includes a tool (`check_user_subscription_status`) that can provide your end-users with a link to their Stripe Customer Billing Portal. This portal allows them to manage their subscriptions, such as canceling them or, if you configure it, switching between different plans.
  128. **Initial Setup (Important):**
  129. By default, the Stripe Customer Billing Portal might not be fully configured in your Stripe account, especially in the test environment.
  130. 1. After setting up your Stripe keys and products (Step 5) and running your server, you can test the `check_user_subscription_status` tool (e.g., via MCP Inspector, or by triggering it through an AI assistant).
  131. 2. If the tool returns a JSON response where `billingPortal.message` contains an error like: *"Could not generate a link to the customer billing portal: No configuration provided and your test mode default configuration has not been created. Provide a configuration or create your default by saving your customer portal settings in test mode at https://dashboard.stripe.com/test/settings/billing/portal."*
  132. 3. You **must** visit the URL provided in that error message (usually `https://dashboard.stripe.com/test/settings/billing/portal`) and save your portal settings in Stripe. This activates the portal for your test environment. You'll need to do a similar check and configuration for your live environment.
  133. Once activated, the `check_user_subscription_status` tool will provide a direct link in the `billingPortal.url` field of its JSON response, which your users can use.
  134. **Allowing Users to Switch Plans (Optional):**
  135. By default, the billing portal allows users to cancel their existing subscriptions. If you offer multiple subscription products for your MCP server and want to allow users to switch between them:
  136. 1. In your Stripe Dashboard, navigate to **Settings** (click the gear icon in the top-right) and then find **Customer portal** under "Billing". (Alternatively, use the direct link: `https://dashboard.stripe.com/settings/billing/portal` for live mode, or `https://dashboard.stripe.com/test/settings/billing/portal` for test mode).
  137. 2. Under the "**Products**" section of the Customer Portal settings page, find "**Subscription products**".
  138. 3. Enable the "**Customers can switch plans**" toggle.
  139. 4. In the "Choose the eligible products that customers can update" subsection that appears, click to "**Find a test product...**" (or "Find a product..." in live mode) and add the other subscription products you want to make available for your users to switch to. The image you provided earlier shows this UI in Stripe.
  140. 5. You can also configure other options here, like allowing customers to change the quantity of their plan if applicable.
  141. This configuration empowers your users to manage their subscriptions more flexibly directly through the Stripe-hosted portal.
  142. ### Step 6: Complete Your Settings
  143. Make sure your `.dev.vars` file has all these values:
  144. ```ini
  145. BASE_URL="http://localhost:8787"
  146. COOKIE_ENCRYPTION_KEY="generate-a-random-string-at-least-32-characters"
  147. GOOGLE_CLIENT_ID="your-google-client-id"
  148. GOOGLE_CLIENT_SECRET="your-google-client-secret"
  149. STRIPE_SECRET_KEY="your-stripe-secret-key"
  150. STRIPE_SUBSCRIPTION_PRICE_ID="your-stripe-price-id"
  151. STRIPE_METERED_PRICE_ID="your-stripe-metered-price-id"
  152. ```
  153. For the `COOKIE_ENCRYPTION_KEY`, you can generate a random string with this command:
  154. ```bash
  155. openssl rand -hex 32
  156. ```
  157. ### Step 7: Start Your Server Locally
  158. 1. Run this command to start your server:
  159. ```bash
  160. npx wrangler dev
  161. ```
  162. 2. Your server will start at `http://localhost:8787`
  163. 3. The main endpoint for AI tools will be at `http://localhost:8787/sse`
  164. ### Step 8: Try It Out
  165. You can test your server by connecting to it with an AI assistant:
  166. 1. Go to [Cloudflare AI Playground](https://playground.ai.cloudflare.com/)
  167. 2. Enter your server URL: `http://localhost:8787/sse`
  168. 3. You'll be redirected to log in with Google
  169. 4. After logging in, you can start testing the tools
  170. Or with Claude Desktop:
  171. 1. Open Claude Desktop
  172. 2. Go to Settings > Developer > Edit Config
  173. 3. Add your server:
  174. ```json
  175. {
  176. "mcpServers": {
  177. "my_server": {
  178. "command": "npx",
  179. "args": [
  180. "mcp-remote",
  181. "http://localhost:8787/sse"
  182. ]
  183. }
  184. }
  185. }
  186. ```
  187. 4. Restart Claude Desktop
  188. 5. Your tools should now be available in Claude
  189. Or with MCP Inspector:
  190. 1. Run MCP Inspector and connect to your server:
  191. ```bash
  192. npx @modelcontextprotocol/inspector@0.11.0
  193. ```
  194. > [!WARNING]
  195. > The latest version of MCP Inspector is 0.12.0 but using npx @modelcontextprotocol/inspector@latest doesn't work right now. Working on it.
  196. 2. Enter your server URL: `http://localhost:8787/sse`
  197. 3. Use the web interface to test and debug your tools
  198. 4. You can directly call your tools, see the request/response data, and quickly iterate during development
  199. ### Step 9: Going Live (Deploying)
  200. When you're ready to make your server available online:
  201. 1. Deploy to Cloudflare:
  202. ```bash
  203. npx wrangler deploy
  204. ```
  205. 2. After deployment, you'll get a URL like `https://your-worker-name.your-account.workers.dev`
  206. 3a. Update your Google OAuth settings:
  207. - Go back to Google Cloud Console > APIs & Services > Credentials.
  208. - Edit your OAuth client.
  209. - Add another redirect URI: `https://your-worker-name.your-account.workers.dev/callback/google`.
  210. - Next, navigate to the "OAuth consent screen" page (still within "APIs & Services").
  211. - Under "Publishing status", if it currently shows "Testing", click the "Publish app" button and confirm to move it to "Production". This allows users outside your GSuite organization to use the login if you initially set it up as "External".
  212. 3b. Update your GitHub OAuth App settings: (optional)
  213. - Go to your GitHub Developer settings > OAuth Apps
  214. - Select your OAuth App
  215. - Update the "Authorization callback URL" to: `https://your-worker-name.your-account.workers.dev/callback/github`
  216. 4. Add your settings to Cloudflare by running these commands (you'll be prompted to enter each value):
  217. ```bash
  218. npx wrangler secret put BASE_URL
  219. npx wrangler secret put COOKIE_ENCRYPTION_KEY
  220. npx wrangler secret put GOOGLE_CLIENT_ID
  221. npx wrangler secret put GOOGLE_CLIENT_SECRET
  222. npx wrangler secret put STRIPE_SECRET_KEY
  223. npx wrangler secret put STRIPE_SUBSCRIPTION_PRICE_ID
  224. npx wrangler secret put STRIPE_METERED_PRICE_ID
  225. ```
  226. For the `BASE_URL`, use your Cloudflare URL: `https://your-worker-name.your-account.workers.dev`
  227. ## Creating Your Own Tools
  228. You can easily create your own AI tools by adding new files to the `src/tools` folder. The project comes with examples of both free and paid tools.
  229. ### Creating a Free Tool
  230. To create a free tool (one that users can access without payment):
  231. 1. Create a new file in the `src/tools` folder (for example: `myTool.ts`)
  232. 2. Copy this template from the existing `add.ts` example:
  233. ```typescript
  234. import { z } from "zod";
  235. import { experimental_PaidMcpAgent as PaidMcpAgent } from "@stripe/agent-toolkit/cloudflare";
  236. export function myTool(agent: PaidMcpAgent<Env, any, any>) {
  237. const server = agent.server;
  238. // @ts-ignore
  239. server.tool(
  240. "my_tool_name", // The tool name
  241. "This tool does something cool.", // Description of what your tool does
  242. { // Input parameters
  243. input1: z.string(), // Parameter definitions using Zod
  244. input2: z.number() // E.g., strings, numbers, booleans
  245. },
  246. async ({ input1, input2 }: { input1: string; input2: number }) => ({
  247. // The function that runs when the tool is called
  248. content: [{ type: "text", text: `You provided: ${input1} and ${input2}` }],
  249. })
  250. );
  251. }
  252. ```
  253. 3. Modify the code to create your own tool:
  254. - Change the function name (`myTool`)
  255. - Change the tool name (`my_tool_name`)
  256. - Update the description
  257. - Define the input parameters your tool needs
  258. - Write the code that runs when the tool is called
  259. 4. Add your tool to `src/tools/index.ts`:
  260. ```typescript
  261. // Add this line with your other exports
  262. export * from './myTool';
  263. ```
  264. 5. Register your tool in `src/index.ts`:
  265. ```typescript
  266. // Inside the init() method, add:
  267. tools.myTool(this);
  268. ```
  269. ### Creating Paid Tools: Subscription, Metered, or One-Time Payment
  270. You can create tools that require payment in three ways: recurring subscriptions, metered usage, or one-time payments.
  271. #### Option 1: Creating a Subscription-Based Paid Tool
  272. This option is suitable if you want to charge users a recurring fee (e.g., monthly) for access to a tool or a suite of tools.
  273. **Stripe Setup for Subscription Billing:**
  274. 1. In your Stripe Dashboard, create a new Product.
  275. 2. Give your product a name (e.g., "Pro Access Tier").
  276. 3. Add a Price to this product:
  277. * Select "Recurring" for the pricing model.
  278. * Set the price amount and billing interval (e.g., $10 per month).
  279. * Save the price.
  280. 4. After creating the price, Stripe will show you the Price ID (e.g., `price_xxxxxxxxxxxxxx`). This is the ID you will use for `STRIPE_SUBSCRIPTION_PRICE_ID` in your `.dev.vars` file and when registering the tool.
  281. **Tool Implementation:**
  282. 1. Create a new file in the `src/tools` folder (for example: `mySubscriptionTool.ts`)
  283. 2. Copy this template from the existing `subscriptionAdd.ts` example:
  284. ```typescript
  285. import { z } from "zod";
  286. import { experimental_PaidMcpAgent as PaidMcpAgent } from "@stripe/agent-toolkit/cloudflare";
  287. import { REUSABLE_PAYMENT_REASON } from "../helpers/constants";
  288. export function mySubscriptionTool(
  289. agent: PaidMcpAgent<Env, any, any>,
  290. env?: { STRIPE_SUBSCRIPTION_PRICE_ID: string; BASE_URL: string }
  291. ) {
  292. const priceId = env?.STRIPE_SUBSCRIPTION_PRICE_ID || null;
  293. const baseUrl = env?.BASE_URL || null;
  294. if (!priceId || !baseUrl) {
  295. throw new Error("Stripe Price ID and Base URL must be provided for paid tools");
  296. }
  297. agent.paidTool(
  298. "my_subscription_tool_name", // The tool name
  299. {
  300. // Input parameters
  301. input1: z.string(), // Parameter definitions using Zod
  302. input2: z.number(), // E.g., strings, numbers, booleans
  303. },
  304. async ({ input1, input2 }: { input1: string; input2: number }) => ({
  305. // The function that runs when the tool is called
  306. content: [
  307. { type: "text", text: `You provided: ${input1} and ${input2}` },
  308. ],
  309. }),
  310. {
  311. priceId, // Uses the Stripe price ID for a subscription product
  312. successUrl: `${baseUrl}/payment/success`,
  313. paymentReason: REUSABLE_PAYMENT_REASON, // General reason shown to user
  314. }
  315. );
  316. }
  317. ```
  318. 3. Modify the code:
  319. * Change the function name (`mySubscriptionTool`)
  320. * Change the tool name (`my_subscription_tool_name`)
  321. * Update the input parameters and the tool's logic.
  322. 4. Add your tool to `src/tools/index.ts`:
  323. ```typescript
  324. // Add this line with your other exports
  325. export * from './mySubscriptionTool';
  326. ```
  327. 5. Register your tool in `src/index.ts`:
  328. ```typescript
  329. // Inside the init() method, add:
  330. tools.mySubscriptionTool(this, {
  331. STRIPE_SUBSCRIPTION_PRICE_ID: this.env.STRIPE_SUBSCRIPTION_PRICE_ID, // Ensure this matches a subscription Price ID
  332. BASE_URL: this.env.BASE_URL
  333. });
  334. ```
  335. #### Option 2: Creating a Metered-Usage Paid Tool
  336. This option is suitable if you want to charge users based on how much they use an MCP tool.
  337. **Stripe Setup for Metered Billing:**
  338. 1. In your Stripe Dashboard, create a new Product.
  339. 2. Add a Price to this product.
  340. * Choose "Standard pricing" or "Package pricing" as appropriate for your model.
  341. * **Under "Price options", check "Usage is metered".**
  342. * You can then define how usage is reported (e.g., "per unit").
  343. * If you want to offer a free tier (like the first 3 uses are free), you can set up "Graduated pricing". For example:
  344. * First 3 units: $0.00 per unit
  345. * Next units (4 and up): $0.10 per unit
  346. 3. After creating the price, Stripe will show you the Price ID (e.g., `price_xxxxxxxxxxxxxx`).
  347. 4. You will also need to define a "meter" in Stripe for this product/price if you haven't already. This meter will have an event name (e.g., `metered_add_usage`) that you'll use in your tool's code. You can usually set this up under the "Usage" tab of your product or when defining the metered price.
  348. **Tool Implementation:**
  349. 1. Create a new file in the `src/tools` folder (e.g., `myMeteredTool.ts`).
  350. 2. Use this template, inspired by the `meteredAdd.ts` example:
  351. ```typescript
  352. import { z } from "zod";
  353. import { experimental_PaidMcpAgent as PaidMcpAgent } from "@stripe/agent-toolkit/cloudflare";
  354. import { METERED_TOOL_PAYMENT_REASON } from "../helpers/constants"; // You might want a specific constant
  355. export function myMeteredTool(
  356. agent: PaidMcpAgent<Env, any, any>,
  357. env?: { STRIPE_METERED_PRICE_ID: string; BASE_URL: string }
  358. ) {
  359. const priceId = env?.STRIPE_METERED_PRICE_ID || null;
  360. const baseUrl = env?.BASE_URL || null;
  361. if (!priceId || !baseUrl) {
  362. throw new Error("Stripe Metered Price ID and Base URL must be provided for metered tools");
  363. }
  364. agent.paidTool(
  365. "my_metered_tool_name", // The tool name
  366. {
  367. // Input parameters
  368. a: z.number(),
  369. b: z.number(),
  370. },
  371. async ({ a, b }: { a: number; b: number }) => {
  372. // The function that runs when the tool is called
  373. // IMPORTANT: Business logic for your tool
  374. const result = a + b; // Example logic
  375. return {
  376. content: [{ type: "text", text: String(result) }],
  377. };
  378. },
  379. {
  380. checkout: {
  381. success_url: `${baseUrl}/payment/success`,
  382. line_items: [
  383. {
  384. price: priceId, // Uses the Stripe Price ID for a metered product
  385. },
  386. ],
  387. mode: 'subscription', // Metered plans are usually set up as subscriptions
  388. },
  389. paymentReason:
  390. "METER INFO: Details about your metered usage. E.g., Your first X uses are free, then $Y per use. " +
  391. METERED_TOOL_PAYMENT_REASON, // Customize this message
  392. meterEvent: "your_meter_event_name_from_stripe", // ** IMPORTANT: Use the event name from your Stripe meter setup **
  393. // e.g., "metered_add_usage"
  394. }
  395. );
  396. }
  397. ```
  398. 3. Modify the code:
  399. * Change the function name (`myMeteredTool`).
  400. * Change the tool name (`my_metered_tool_name`).
  401. * Update the input parameters and the tool's core logic.
  402. * **Crucially, update `meterEvent`** to match the event name you configured in your Stripe meter.
  403. * Customize the `paymentReason` to clearly explain the metered billing to the user.
  404. 4. Add your tool to `src/tools/index.ts`:
  405. ```typescript
  406. // Add this line with your other exports
  407. export * from './myMeteredTool';
  408. ```
  409. 5. Register your tool in `src/index.ts`:
  410. ```typescript
  411. // Inside the init() method, add:
  412. tools.myMeteredTool(this, {
  413. STRIPE_METERED_PRICE_ID: this.env.STRIPE_METERED_PRICE_ID, // Ensure this matches your metered Price ID
  414. BASE_URL: this.env.BASE_URL
  415. });
  416. ```
  417. #### Option 3: Creating a One-Time Payment Tool
  418. This option is suitable if you want to charge users a single fee for access to a tool, rather than a recurring subscription or usage-based metering.
  419. **Stripe Setup for One-Time Payments:**
  420. 1. In your Stripe Dashboard, create a new Product.
  421. 2. Give your product a name (e.g., "Single Report Generation").
  422. 3. Add a Price to this product:
  423. * Select "One time" for the pricing model.
  424. * Set the price amount.
  425. * Save the price.
  426. 4. After creating the price, Stripe will show you the Price ID (e.g., `price_xxxxxxxxxxxxxx`). This is the ID you will use for a new environment variable, for example, `STRIPE_ONE_TIME_PRICE_ID`.
  427. **Tool Implementation:**
  428. 1. Create a new file in the `src/tools` folder (for example: `myOnetimeTool.ts`).
  429. 2. Use this template, inspired by the `onetimeAdd.ts` example:
  430. ```typescript
  431. import { z } from "zod";
  432. import { experimental_PaidMcpAgent as PaidMcpAgent } from "@stripe/agent-toolkit/cloudflare";
  433. import { REUSABLE_PAYMENT_REASON } from "../helpers/constants"; // Or a more specific reason
  434. export function myOnetimeTool(
  435. agent: PaidMcpAgent<Env, any, any>, // Adjust AgentProps if needed
  436. env?: { STRIPE_ONE_TIME_PRICE_ID: string; BASE_URL: string }
  437. ) {
  438. const priceId = env?.STRIPE_ONE_TIME_PRICE_ID || null;
  439. const baseUrl = env?.BASE_URL || null;
  440. if (!priceId || !baseUrl) {
  441. throw new Error("Stripe One-Time Price ID and Base URL must be provided for this tool");
  442. }
  443. agent.paidTool(
  444. "my_onetime_tool_name", // The tool name
  445. {
  446. // Input parameters
  447. input1: z.string(), // Parameter definitions using Zod
  448. },
  449. async ({ input1 }: { input1: string }) => ({
  450. // The function that runs when the tool is called
  451. content: [
  452. { type: "text", text: `You processed: ${input1}` },
  453. ],
  454. }),
  455. {
  456. checkout: { // Defines a one-time payment checkout session
  457. success_url: `${baseUrl}/payment/success`,
  458. line_items: [
  459. {
  460. price: priceId, // Uses the Stripe Price ID for a one-time payment product
  461. quantity: 1,
  462. },
  463. ],
  464. mode: 'payment', // Specifies this is a one-time payment, not a subscription
  465. },
  466. paymentReason: "Enter a clear reason for this one-time charge. E.g., 'Unlock premium feature X for a single use.'", // Customize this message
  467. }
  468. );
  469. }
  470. ```
  471. 3. Modify the code:
  472. * Change the function name (`myOnetimeTool`).
  473. * Change the tool name (`my_onetime_tool_name`).
  474. * Update the input parameters and the tool's core logic.
  475. * Ensure the `checkout.mode` is set to `'payment'`.
  476. * Customize the `paymentReason` to clearly explain the one-time charge to the user.
  477. 4. Add your tool to `src/tools/index.ts`:
  478. ```typescript
  479. // Add this line with your other exports
  480. export * from './myOnetimeTool';
  481. ```
  482. 5. Register your tool in `src/index.ts`:
  483. ```typescript
  484. // Inside the init() method, add:
  485. tools.myOnetimeTool(this, {
  486. STRIPE_ONE_TIME_PRICE_ID: this.env.STRIPE_ONE_TIME_PRICE_ID, // Ensure this matches your one-time payment Price ID
  487. BASE_URL: this.env.BASE_URL
  488. });
  489. ```
  490. 6. Remember to add `STRIPE_ONE_TIME_PRICE_ID` to your `.dev.vars` file and Cloudflare secrets:
  491. In `.dev.vars`:
  492. ```ini
  493. STRIPE_ONE_TIME_PRICE_ID="price_your-onetime-price-id-here"
  494. ```
  495. And for production:
  496. ```bash
  497. npx wrangler secret put STRIPE_ONE_TIME_PRICE_ID
  498. ```
  499. You can create different paid tools with different Stripe products (subscription or metered) by creating additional price IDs in your Stripe dashboard and passing them as environment variables.
  500. ### What Happens When a Free User Tries a Paid Tool
  501. When a user tries to access a paid tool without having purchased it:
  502. 1. The server checks if they've already paid
  503. 2. If not, the AI assistant will automatically prompt them with a checkout link
  504. 3. After completing payment on Stripe they should be able to use the tool immediately
  505. ## Future Enhancements (Optional)
  506. ### Setting Up Stripe Webhooks
  507. The basic setup above is all you need to get started. The built-in Stripe integration verifies payments directly when users try to access paid tools - it checks both one-time payments and subscriptions automatically.
  508. Webhooks are completely optional but could be useful for more complex payment scenarios in the future, like:
  509. - Building a customer dashboard to display subscription status
  510. - Implementing usage-based billing with metering
  511. - Creating custom workflows when subscriptions are created or canceled
  512. - Handling refunds and disputes with special logic
  513. If you ever want to add webhook support:
  514. 1. Go to your Stripe Dashboard > Developers > Webhooks
  515. 2. Click "Add endpoint"
  516. 3. For the endpoint URL:
  517. - For local development: `http://localhost:8787/webhooks/stripe`
  518. - For production: `https://your-worker-name.your-account.workers.dev/webhooks/stripe`
  519. 4. For "Events to send", select events relevant to your needs, such as:
  520. - checkout.session.completed
  521. - invoice.payment_succeeded
  522. - customer.subscription.updated
  523. 5. After creating the webhook, copy the "Signing secret"
  524. 6. Add this value to your settings:
  525. - For local development, add to `.dev.vars`:
  526. ```ini
  527. STRIPE_WEBHOOK_SECRET="whsec_your-webhook-secret-here"
  528. ```
  529. - For production, set it using Wrangler:
  530. ```bash
  531. npx wrangler secret put STRIPE_WEBHOOK_SECRET
  532. ```
  533. ## Need Help?
  534. If you encounter any bugs or have issues with the boilerplate, please submit an issue on the GitHub repository. Please note that this project is provided as-is and does not include direct support.

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.