Skip to main content
Glama
friczerocom-cpu

contextslim

ContextSlim Python SDK

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

ContextSlim prunes massive JSON payloads by up to 75%+, enforces strict token budgets, and handles autonomous HTTP 402 EIP-712 micropayments—keeping Python AI agents (LangChain, CrewAI, AutoGen, LlamaIndex) fast, cost-effective, and deterministically within LLM context limits.


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

542 Tokens

136 Tokens

74.8% Token Saved

406 Tokens saved in initial pruning

fetch_result (Targeted Path)

542 Tokens

23 Tokens

95.7% Savings

Surgical 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 Python AI Agent framework, the Model Context Protocol (MCP), and the Base blockchain:

+-------------------+       1. MCP Tool Call       +------------------------+
|  AI Agent / LLM   | ---------------------------> |  contextslim           |
| (CrewAI/LangChain)| <--------------------------- |  (Python SDK Engine)   |
+-------------------+     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 lightweight native package from PyPI:

pip install contextslim eth-account python-dotenv

MCP Client Configurations

1. Claude Desktop Integration

Add the following configuration to your claude_desktop_config.json file:

{
  "mcpServers": {
    "contextslim": {
      "command": "uvx",
      "args": ["contextslim"],
      "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 os
from dotenv import load_dotenv
from eth_account import Account
from contextslim import ContextSlimClient

load_dotenv()

def main():
    # 1. Initialize Local Signer (Private key isolated in memory)
    signer = Account.from_key(os.getenv("PRIVATE_KEY"))

    # 2. Instantiate ContextSlim Client
    client = ContextSlimClient(
        endpoint=os.getenv("ENDPOINT_URL", "https://contextslim.friczero.com"),
        signer=signer,
        allowance_budget=0.005,  # Optional: Enables Session Pass to avoid signing every query
        max_token_budget=1000,
    )

    # 3. Prune Massive Payload (optimize_context)
    heavy_payload = {
        "company": "Acme Corp International",
        "key_team": [
            {"name": "Alice Gomez", "role": "CTO"},
            {"name": "Carlos M.", "role": "CEO"},
        ],
        "historical_logs": [f"Log entry #{i + 1}: Activity sweep" for i in range(100)],
    }

    print("Optimizing massive context...")
    prep = client.call_tool("optimize_context", {
      "data": heavy_payload,
      "maxTokenBudget": 150
    })

    res = prep.get("result", {})
    ref_id = res.get("toolResultReference", {}).get("referenceId") or res.get("referenceId")
    
    print(f"Reference Cached in KV: {ref_id}")
    print(f"Saved Tokens: {prep.get('metrics', {}).get('savedTokens')}")
    print(f"Compression Ratio: {prep.get('metrics', {}).get('reductionPercentage')}")

    # 4. Targeted Path Extraction (fetch_result)
    print("Retrieving only 'key_team[0].name'...")
    extracted = client.call_tool("fetch_result", {
      "referenceId": ref_id,
      "paths": ["company", "key_team[0].name"]
    })

    print("Result:", extracted.get("result"))
    # Returns only 23 tokens: {"company": "Acme Corp International", "key_team": [{"name": "Alice Gomez"}]}

if __name__ == "__main__":
    main()

Advanced Signer Setup (Production & Enterprise)

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

ContextSlimClient accepts any compatible signing interface (wrapping EIP-712 / ERC-3009 signatures), allowing seamless integration with Cloud Key Management Services (KMS), Hardware Security Modules (HSMs), and Vaults:

1. AWS KMS / HashiCorp Vault Integration

Keep keys non-exportable inside dedicated cloud HSMs using a custom signer wrapper:

from contextslim import ContextSlimClient
from my_kms_signer import AWSKMSSigner  # Custom wrapper around boto3 KMS sign_digest

kms_signer = AWSKMSSigner(key_id="arn:aws:kms:us-east-1:123456789012:key/your-agent-key-id")

client = ContextSlimClient(
    endpoint="https://contextslim.friczero.com",
    signer=kms_signer,
)

2. Turnkey / Web3.py Signers

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

from contextslim import ContextSlimClient
from turnkey import TurnkeyAccount

turnkey_signer = TurnkeyAccount(
    organization_id=os.getenv("TURNKEY_ORGANIZATION_ID"),
    wallet_address=os.getenv("TURNKEY_WALLET_ADDRESS"),
)

client = ContextSlimClient(
    endpoint="https://contextslim.friczero.com",
    signer=turnkey_signer,
)

API Reference

ContextSlimClient(endpoint, signer, allowance_budget, max_token_budget)

Option

Type

Default

Description

endpoint

str

Required

Base URL of the ContextSlim Worker (https://contextslim.friczero.com).

signer

LocalAccount

Required

eth_account LocalAccount or KMS Signer for ERC-3009/EIP-712 payment authorizations.

allowance_budget

float

0.0

USDC budget to pre-approve a Session Pass (base price: $0.001 USDC/call; on-chain settlement triggers at $0.005 USDC).

max_token_budget

int

1000

Default response token limit.


Client Methods

client.call_tool(name, args)

Unified tool invocation method compatible with MCP JSON-RPC.

1. optimize_context Tool

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

  • Parameters (args dict):

    • data (dict, required) - Full JSON payload to optimize.

    • maxTokenBudget (int, optional) - Hard token limit for the response payload.

  • Response:

{
    "status": "success",
    "result": {
        "toolResultReference": {"referenceId": "ref_ef17a253", "expiresIn": "3600s"},
        # ... pruned payload
    },
    "metrics": {
        "savedTokens": "406",
        "reductionPercentage": "74.8%",
        "strategy": "recursive:arrays(47_items)",
    },
}
2. fetch_result Tool

Retrieves exact data subsets from a cached reference ID.

  • Parameters (args dict):

    • referenceId (str, required) - ID returned by optimize_context.

    • paths (list[str], optional) - Dot-notation field paths to extract (e.g., ["company", "key_team[0].name"]).

  • Response:

{
    "status": "success",
    "referenceId": "ref_ef17a253",
    "retrievedTokens": 23,
    "result": {
        "company": "Acme Corp International",
        "key_team": [{"name": "Alice Gomez"}],
    },
}

Security & Resilience

  • Cryptographic Isolation: EIP-712 / ERC-3009 x402 payment challenge signing happens strictly in local process memory via eth-account or your cloud KMS. No private keys or seed phrases ever leave your client 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 allowance_budget 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.

Maintenance

ActivityMaintained
ResponsivenessSyncing

Related MCP Connectors

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/friczerocom-cpu/contextslim-python'

If you have feedback or need assistance with the MCP directory API, please join our Discord server