npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@shade402/langchain

v0.0.1

Published

LangChain.js integration for X402 payment protocol

Readme

@shade402/langchain

LangChain.js integration for X402 payment protocol. Enables AI agents built with LangChain to autonomously make payments for API access.

Overview

The LangChain package provides a payment tool that can be integrated into LangChain agents, allowing them to automatically pay for access to X402-protected APIs. This enables autonomous AI agents to access paid APIs without manual intervention.

Features

  • LangChain tool integration for X402 payments
  • Automatic payment handling in agent workflows
  • Configurable payment limits for safety
  • Support for all HTTP methods
  • Full TypeScript support
  • Seamless integration with LangChain agents

Installation

npm install @shade402/langchain
# or
pnpm add @shade402/langchain
# or
yarn add @shade402/langchain

Dependencies

  • @shade402/core: Core X402 protocol implementation
  • @shade402/client: X402 HTTP client
  • @solana/web3.js: Solana wallet operations
  • @langchain/core: LangChain core types
  • langchain: LangChain.js framework
  • zod: Schema validation

Usage

Basic Setup

import { createX402PaymentTool } from '@shade402/langchain';
import { AgentExecutor, createOpenAIFunctionsAgent } from 'langchain/agents';
import { ChatOpenAI } from '@langchain/openai';
import { Keypair } from '@solana/web3.js';

// Create wallet for agent
const wallet = Keypair.generate();

// Create payment tool
const paymentTool = createX402PaymentTool({
  walletKeypair: wallet,
  rpcUrl: 'https://api.devnet.solana.com',
  maxPayment: '1.0', // Maximum payment amount in USD
  name: 'x402_payment',
  description: 'Make a payment to access a paid API endpoint'
});

// Create agent with payment tool
const model = new ChatOpenAI({ temperature: 0 });
const tools = [paymentTool];
const agent = await createOpenAIFunctionsAgent({
  llm: model,
  tools,
  prompt: /* your prompt */
});

const executor = new AgentExecutor({
  agent,
  tools,
  verbose: true
});

// Agent can now use the payment tool
const result = await executor.invoke({
  input: 'Fetch data from https://api.example.com/premium-data'
});

Advanced Configuration

import { createX402PaymentTool } from '@shade402/langchain';
import { Keypair } from '@solana/web3.js';

const wallet = Keypair.generate();

const paymentTool = createX402PaymentTool({
  walletKeypair: wallet,
  rpcUrl: process.env.SOLANA_RPC_URL,
  maxPayment: '5.0', // Allow up to $5 per payment
  name: 'api_payment',
  description: 'Pay for API access using X402 protocol. Use this when you need to access a paid API endpoint.',
  allowLocal: false // Set to true for localhost in development
});

Using the Tool Class

You can also use the class directly for more control:

import { X402PaymentTool } from '@shade402/langchain';
import { Keypair } from '@solana/web3.js';

const wallet = Keypair.generate();

const paymentTool = new X402PaymentTool({
  walletKeypair: wallet,
  rpcUrl: 'https://api.devnet.solana.com',
  maxPayment: '1.0',
  name: 'x402_payment',
  description: 'Make X402 payment for API access'
});

// Add to agent tools
const tools = [paymentTool];

API Reference

createX402PaymentTool

Factory function to create an X402 payment tool for LangChain.

function createX402PaymentTool(
  options: X402PaymentToolOptions
): DynamicStructuredTool

Parameters:

  • options.walletKeypair: Solana wallet keypair for making payments
  • options.rpcUrl: Optional Solana RPC URL (default: devnet)
  • options.maxPayment: Maximum payment amount (default: '1.0')
  • options.name: Tool name (default: 'x402_payment')
  • options.description: Tool description
  • options.allowLocal: Allow localhost URLs (default: false)

Returns: LangChain DynamicStructuredTool instance

Tool Schema:

  • url: string - The API endpoint URL to access
  • method: string (optional) - HTTP method (GET, POST, PUT, DELETE), default: 'GET'

X402PaymentTool

Class-based implementation of the payment tool.

class X402PaymentTool extends DynamicStructuredTool

Constructor:

new X402PaymentTool(options: X402PaymentToolOptions)

Methods:

  • async execute(url: string, method?: string): Promise<string> - Execute payment and fetch API

Examples

Simple Agent with Payment Tool

import { createX402PaymentTool } from '@shade402/langchain';
import { AgentExecutor, createOpenAIFunctionsAgent } from 'langchain/agents';
import { ChatOpenAI } from '@langchain/openai';
import { Keypair } from '@solana/web3.js';
import { ChatPromptTemplate } from '@langchain/core/prompts';

const wallet = Keypair.generate();

const paymentTool = createX402PaymentTool({
  walletKeypair: wallet,
  rpcUrl: 'https://api.devnet.solana.com',
  maxPayment: '1.0'
});

const model = new ChatOpenAI({ temperature: 0 });
const prompt = ChatPromptTemplate.fromMessages([
  ['system', 'You are a helpful assistant that can access paid APIs.'],
  ['human', '{input}']
]);

const agent = await createOpenAIFunctionsAgent({
  llm: model,
  tools: [paymentTool],
  prompt
});

const executor = new AgentExecutor({
  agent,
  tools: [paymentTool],
  verbose: true
});

const result = await executor.invoke({
  input: 'Get the latest data from https://api.example.com/data'
});

Agent with Multiple Tools

import { createX402PaymentTool } from '@shade402/langchain';
import { DynamicStructuredTool } from '@langchain/core/tools';
import { z } from 'zod';
import { AgentExecutor, createOpenAIFunctionsAgent } from 'langchain/agents';
import { ChatOpenAI } from '@langchain/openai';
import { Keypair } from '@solana/web3.js';

const wallet = Keypair.generate();

// Payment tool
const paymentTool = createX402PaymentTool({
  walletKeypair: wallet,
  maxPayment: '2.0'
});

// Other tools
const searchTool = new DynamicStructuredTool({
  name: 'web_search',
  description: 'Search the web',
  schema: z.object({
    query: z.string()
  }),
  func: async ({ query }) => {
    // Your search implementation
    return 'Search results...';
  }
});

const tools = [paymentTool, searchTool];

const model = new ChatOpenAI({ temperature: 0 });
const agent = await createOpenAIFunctionsAgent({
  llm: model,
  tools,
  prompt: /* your prompt */
});

const executor = new AgentExecutor({ agent, tools });

Error Handling

import { createX402PaymentTool } from '@shade402/langchain';
import { Keypair } from '@solana/web3.js';

const wallet = Keypair.generate();

const paymentTool = createX402PaymentTool({
  walletKeypair: wallet,
  maxPayment: '1.0'
});

// Tool will return error messages as strings
// Agent should handle these in its reasoning
const result = await paymentTool.invoke({
  url: 'https://api.example.com/data',
  method: 'GET'
});

if (result.startsWith('Payment error:')) {
  console.error('Payment failed:', result);
}

Production Configuration

import { createX402PaymentTool } from '@shade402/langchain';
import { Keypair } from '@solana/web3.js';
import { readFileSync } from 'fs';

// Load wallet from secure storage
const walletKeypair = Keypair.fromSecretKey(
  Buffer.from(JSON.parse(readFileSync('wallet.json', 'utf-8')))
);

const paymentTool = createX402PaymentTool({
  walletKeypair,
  rpcUrl: process.env.SOLANA_MAINNET_RPC_URL,
  maxPayment: '10.0', // Higher limit for production
  name: 'x402_payment',
  description: 'Pay for API access. Only use when explicitly needed.',
  allowLocal: false
});

Tool Behavior

The payment tool automatically:

  1. Detects when a 402 Payment Required response is received
  2. Parses the payment request
  3. Creates and broadcasts the payment transaction
  4. Retries the original request with payment authorization
  5. Returns the API response data

If payment fails, the tool returns an error message that the agent can use in its reasoning.

Integration Tips

Prompt Engineering

Include instructions about when to use the payment tool:

You have access to a payment tool for accessing paid APIs. Use it only when:
1. The API explicitly requires payment
2. The payment amount is reasonable
3. You have been instructed to access the paid API

Payment Limits

Set appropriate maxPayment limits based on your use case:

  • Development: $0.10 - $1.00
  • Testing: $1.00 - $5.00
  • Production: Based on your budget and use case

Wallet Management

  • Store wallet keys securely (environment variables, key management service)
  • Use separate wallets for different agents if needed
  • Monitor wallet balances
  • Set up alerts for low balances

Security Considerations

  • Never expose wallet private keys in client-side code
  • Use environment variables for sensitive configuration
  • Set appropriate maxPayment limits to prevent excessive payments
  • Monitor agent behavior and payment patterns
  • Use mainnet RPC endpoints for production
  • Keep wallet keys secure and rotate them regularly
  • Set allowLocal: false in production

TypeScript Support

The package is written in TypeScript and provides full type definitions:

import type {
  X402PaymentToolOptions
} from '@shade402/langchain';

License

MIT