BACK TO BLOG

Integrating Polar with xmcp


guides

Learn how to add paywalls with license keys and track tool usage using Polar.

Install Dependencies

Start by installing the Polar plugin:

npm install @xmcp-dev/polar

Initialize

To initialize the provider and access the validation methods, you need to create a new instance:

import { PolarProvider } from "@xmcp-dev/polar";

export const polar = PolarProvider.getInstance({
  type: "sandbox", // or "production", depending on your environment
  token: process.env.POLAR_TOKEN,
  organizationId: process.env.POLAR_ORGANIZATION_ID,
  productId: process.env.POLAR_PRODUCT_ID,
});

The configuration schema is as follows:

interface Configuration {
  type?: "production" | "sandbox";
  token: string;
  organizationId: string;
  productId: string;
}
  • If type is not set, it will default to "production". This affects the token used to authenticate.
  • The license key should be provided in the license-key header. This is not customizable.

On polar.sh, create a new product with your desired payment configuration and add the "license key" benefit to the product. You can also add a "meter credit" benefit to the product to track tool usage, and limit the usage of the key.

Tool Integration

To paywall a tool, you can use the validateLicenseKey method to validate the license key and check if the user has access to the tool. Remember you can use the xmcp/headers utility to access the headers of the request and intercept this value.

const licenseKey = headers()["license-key"];
const response = await polar.validateLicenseKey(licenseKey);

The response object will look like this:

{
  valid: boolean;
  code: string;
  message: string;
}

You can then access this response object and return the appropriate auto-generated messages as follows:

if (!response.valid) {
  return response.message;
}

This will prompt the user to the checkout URL in case the license key is invalid.

Usage Tracking

To track usage we recommend setting a "meter credit" benefit to the product with the following configuration:

Alt text

Then you can pass an event object to the validateLicenseKey method to track usage.

const event = {
  name: "tool_call_event",
  metadata: { tool_name: "tool_name", calls: 1 },
};

const response = await polar.validateLicenseKey(licenseKey, event);

The event object metadata can have any type of string or number as values.

Conclusion

You can now add paywalls to your tools and track usage for billing with Polar!

For more information, you can check the Polar documentation. If you have any questions, you can reach out to us on Discord.