contextslim

contextslim

Enables AI agents to optimize context by pruning large JSON payloads, enforcing token budgets, and handling x402 micropayments via Base blockchain.

Category
访问服务器

README

ContextSlim TypeScript SDK

High-performance M2M context middleware and x402 micropayment engine for AI Agents and MCP tools on Base.

ContextSlim prunes massive JSON payloads by up to 85%, enforces strict token budgets, and handles autonomous HTTP 402 EIP-712 micropayments—keeping agent execution fast, cost-effective, and deterministically within LLM context limits.

smithery badge


Proven E2E Benchmarks

Real-world test suite performance measured over live execution on Cloudflare KV + Base Sepolia:

MCP Tool / Operation Input Payload Output Payload Reduction / Impact Performance Metric
optimize_context 622 Tokens 94 Tokens 84.9% Token Saved 528 Tokens saved in array pruning
fetch_result (Targeted Path) 622 Tokens 9 Tokens 98.5% Savings Instant extraction via JSONPath
Session Pass (2nd Query) On-chain Auth Cache Auth 70% Latency Drop 0.43s $\rightarrow$ 0.13s execution speed

Architecture & Protocol Flow

ContextSlim seamlessly sits between your AI Agent framework, the Model Context Protocol (MCP), and the Base blockchain:

+-------------------+       1. MCP Tool Call       +------------------------+
|  AI Agent / LLM   | ---------------------------> |  @contextslim/sdk      |
| (Claude / Cursor) | <--------------------------- |  (TS Engine Client)    |
+-------------------+     4. Pruned Payload        +------------------------+
                                                               |        ^
                                             2. x402 Payment   |        | 3. Optimized Data
                                                Challenge/Pass |        |    & Reference ID
                                                               v        |
                                                   +--------------------------------+
                                                   | ContextSlim Worker Engine      |
                                                   | (Cloudflare KV + Pruner Engine)|
                                                   +--------------------------------+
                                                                   |
                                                                   v (On-Chain Settlement)
                                                   +--------------------------------+
                                                   | Base Network (USDC / ERC-3009) |
                                                   +--------------------------------+

Installation

Install the agnostic SDK optimized for Node.js (v18+), Bun, Deno, and Cloudflare Workers:

npm install @contextslim/sdk ethers dotenv

MCP Client Configurations

1. Claude Desktop Integration

Add the following configuration to your claude_desktop_config.json file:

{
  "mcpServers": {
    "contextslim": {
      "command": "npx",
      "args": ["-y", "@contextslim/sdk"],
      "env": {
        "ENDPOINT_URL": "https://contextslim.friczero.com",
        "PRIVATE_KEY": "0x_YOUR_AGENT_PRIVATE_KEY"
      }
    }
  }
}

2. Cursor IDE (.cursor/mcp.json)

{
  "mcpServers": {
    "contextslim": {
      "url": "https://contextslim.friczero.com/message"
    }
  }
}

3. Smithery CLI

One-click installation via Smithery:

npx -y @smithery/cli install contextslim --client claude

30-Second Quickstart

This script initializes the client with an active Session Pass ($0.005 USDC), prunes a massive JSON payload, and retrieves specific fields with ultra-low latency:

import { ContextSlimClient } from "@contextslim/sdk";
import { Wallet } from "ethers";
import * as dotenv from "dotenv";

dotenv.config();

async function main() {
  // 1. Initialize Local Signer (Private key isolated in memory)
  const wallet = new Wallet(process.env.PRIVATE_KEY!);

  // 2. Instantiate ContextSlim Client
  const client = new ContextSlimClient({
    endpoint: process.env.ENDPOINT_URL || "https://contextslim.friczero.com",
    signer: wallet,
    allowanceBudget: 0.005, // Optional: Enables Session Pass to avoid signing every query
    maxTokenBudget: 1000,
  });

  // 3. Prune Massive Payload (optimize_context)
  const heavyPayload = {
    critical_alert: {
      severity: "CRITICAL",
      system: "database-cluster-primary",
      message: "Connection pool exhausted on port 5432",
    },
    system_status: { cpu_load: "88%", memory_used: "14.2GB" },
    logs: Array.from({ length: 100 }, (_, i) => `Log entry #${i + 1}: Activity sweep`),
  };

  console.log("Optimizing massive context...");
  const prep = await client.callTool("optimize_context", {
    data: heavyPayload,
    maxTokenBudget: 150,
  });

  const res = prep.result || {};
  const refId = res.toolResultReference?.referenceId || res.referenceId;
  console.log(`Reference Cached in KV: ${refId}`);
  console.log(`Saved Tokens: ${prep.metrics?.savedTokens}`);
  console.log(`Compression Ratio: ${prep.metrics?.reductionPercentage}`);

  // 4. Targeted Path Extraction (fetch_result)
  console.log("Retrieving only 'critical_alert.severity'...");
  const extracted = await client.callTool("fetch_result", {
    referenceId: refId,
    paths: ["critical_alert.severity"],
  });

  console.log("Result:", JSON.stringify(extracted?.result ?? {}, null, 2));
  // Returns only 9 tokens: { critical_alert: { severity: 'CRITICAL' } }
}

main().catch(console.error);

Advanced Signer Setup (Production & Enterprise)

While passing a raw ethers.Wallet initialized from an environment variable works for local development, production AI agents should avoid storing plain-text private keys in .env files.

ContextSlimClient accepts any standard ethers.Signer interface, allowing seamless integration with Hardware Security Modules (HSMs), Cloud Key Management Services (KMS), and Multi-Party Computation (MPC) infrastructure:

1. AWS KMS / Cloud HSM

Keep keys non-exportable inside dedicated cloud HSMs:

import { KmsSigner } from "aws-kms-ethers-signer";
import { ContextSlimClient } from "@contextslim/sdk";

const kmsSigner = new KmsSigner({
  keyId: "arn:aws:kms:us-east-1:123456789012:key/your-agent-key-id",
});

const client = new ContextSlimClient({
  endpoint: "https://contextslim.friczero.com",
  signer: kmsSigner, // Native Ethers Signer wrapping AWS KMS
});

2. Turnkey / Non-Custodial MPC Wallets

Isolate credentials for serverless agents or multi-tenant agent architectures:

import { TurnkeySigner } from "@turnkey/ethers";
import { ContextSlimClient } from "@contextslim/sdk";

const turnkeySigner = new TurnkeySigner({
  client: turnkeyClient,
  organizationId: process.env.TURNKEY_ORGANIZATION_ID!,
  signWith: process.env.TURNKEY_WALLET_ADDRESS!,
});

const client = new ContextSlimClient({
  endpoint: "https://contextslim.friczero.com",
  signer: turnkeySigner,
});

API Reference

new ContextSlimClient(options)

Option Type Default Description
endpoint string Required Base URL of the ContextSlim Worker (https://contextslim.friczero.com).
signer ethers.Signer Required Ethers Signer implementation for ERC-3009/EIP-712 payment authorizations.
allowanceBudget number 0 USDC budget to pre-approve a Session Pass (base price: $0.001 USDC/call; on-chain settlement triggers at $0.005 USDC).
maxTokenBudget number 1000 Default response token limit.

client.callTool(name, params)

Unified invocation compatible with MCP JSON-RPC.

1. optimize_context Tool

Reduces complex JSON structures while preserving critical fields and inserting truncated reference markers (_slim).

  • Parameters:

    • data (object, required) - Full JSON payload to optimize.
    • maxTokenBudget (number, optional) - Hard token limit for the response payload.
  • Response:

{
  status: "success",
  result: {
    toolResultReference: { referenceId: "ref_ef17a253", expiresIn: "3600s" },
    // ... pruned payload
  },
  metrics: {
    savedTokens: "528",
    reductionPercentage: "84.9%",
    strategy: "recursive:arrays(47_items)"
  }
}

2. fetch_result Tool

Retrieves exact data subsets from a cached reference ID.

  • Parameters:

    • referenceId (string, required) - ID returned by optimize_context.
    • paths (string[], optional) - Dot-notation field paths to extract (e.g., ["user.id", "items[0].price"]).
  • Response:

{
  status: "success",
  referenceId: "ref_ef17a253",
  retrievedTokens: 9,
  result: { critical_alert: { severity: "CRITICAL" } }
}

Security & Resilience

  • Cryptographic Isolation: EIP-712 / ERC-3009 x402 payment challenge signing happens strictly within your local process or designated KMS signer. No private keys or seed phrases ever leave your execution environment.
  • Anti-Replay Protection: Every payment challenge issued by the HTTP 402 server includes time-bound single-use nonces. Reusing X-PAYMENT headers is strictly rejected.
  • Session Pass Mechanism: Setting an allowanceBudget issues an encrypted session pass, amortizing on-chain verification and speeding up subsequent KV fetches to an average execution speed of 0.13 seconds.

License

This project is licensed under the MIT License.

推荐服务器

Baidu Map

Baidu Map

百度地图核心API现已全面兼容MCP协议,是国内首家兼容MCP协议的地图服务商。

官方
精选
JavaScript
Playwright MCP Server

Playwright MCP Server

一个模型上下文协议服务器,它使大型语言模型能够通过结构化的可访问性快照与网页进行交互,而无需视觉模型或屏幕截图。

官方
精选
TypeScript
Magic Component Platform (MCP)

Magic Component Platform (MCP)

一个由人工智能驱动的工具,可以从自然语言描述生成现代化的用户界面组件,并与流行的集成开发环境(IDE)集成,从而简化用户界面开发流程。

官方
精选
本地
TypeScript
Audiense Insights MCP Server

Audiense Insights MCP Server

通过模型上下文协议启用与 Audiense Insights 账户的交互,从而促进营销洞察和受众数据的提取和分析,包括人口统计信息、行为和影响者互动。

官方
精选
本地
TypeScript
VeyraX

VeyraX

一个单一的 MCP 工具,连接你所有喜爱的工具:Gmail、日历以及其他 40 多个工具。

官方
精选
本地
graphlit-mcp-server

graphlit-mcp-server

模型上下文协议 (MCP) 服务器实现了 MCP 客户端与 Graphlit 服务之间的集成。 除了网络爬取之外,还可以将任何内容(从 Slack 到 Gmail 再到播客订阅源)导入到 Graphlit 项目中,然后从 MCP 客户端检索相关内容。

官方
精选
TypeScript
Kagi MCP Server

Kagi MCP Server

一个 MCP 服务器,集成了 Kagi 搜索功能和 Claude AI,使 Claude 能够在回答需要最新信息的问题时执行实时网络搜索。

官方
精选
Python
e2b-mcp-server

e2b-mcp-server

使用 MCP 通过 e2b 运行代码。

官方
精选
Neon MCP Server

Neon MCP Server

用于与 Neon 管理 API 和数据库交互的 MCP 服务器

官方
精选
Exa MCP Server

Exa MCP Server

模型上下文协议(MCP)服务器允许像 Claude 这样的 AI 助手使用 Exa AI 搜索 API 进行网络搜索。这种设置允许 AI 模型以安全和受控的方式获取实时的网络信息。

官方
精选