Skip to content
All writing

Escaping the MCP Token Penalty: Building High-Bandwidth CLI Tools

MCPs are known to be context eaters. LLMS are pretty good at using CLIs. In this post I explain how do I created custom HTTP client and wrapped it in CLI. This combination allows LLMS to have high bandwidth tools call and avoid token penalty associated with MCPs.

Author
Tushar Khairnar
Published
Revised
Not revised
Length
10 min read
Cover image for Escaping the MCP Token Penalty: Building High-Bandwidth CLI Tools

Introduction

For last few week I have been using Claude code(CC) extensively and I have observed that CC is able to use Bash Tool effectively - searching, grepping, curl-ing implementing unix's core philosophy of having one tool doing one thing. CC is able to compose several commands - cat, curl, sed, grep, curl, find, docker, github cli, jq, head, tail. But it had to do multi-hop gymnastics when it came to test or invoke application endpoints during debug sessions. MCP is exactly designed for such scenarios where one can extend LLM's ability to bring external context into its window.

Why MCP is needed?

MCP was designed to give LLM set of tools that it can not create or execute on its own. For example. LLM is able to generate flow diagram or sequence diagram markup but can not generate its graphical representation. So one can write an MCP server which can accept textual markup generated and generate PNG or JPEG. Thus one can have an agent (with MCP enabled) that reads all source code files, figures out relationships and execution flow, generate markups for class relationships, entire-relationships, generate flow, cloud infrastructure etc. and invoke tool to embed images into final generated documentation and create HTML/JS/CSS powered documentation site. Agent thus can update the project documentation site anytime. Any changes in the architecture or logic flow will automatically updated not in text but also in visual representation.

Why MCP is not the optimal solution

  1. MCP eats your context window - the most precious resource - more important than token cost. You can be smart to disable MCP when you know you don't need it but when you are invoking agentic prompt which can itself divide into multiple tasks, agents can never know beforehand and can disable/enable MCP at runtime.
  2. MCP is expensive - MCP not only eats your context but it travel to-and-fro eating tokens. This looks like point 1 but substantial difference here is that tool and tool result are required to preserve. In fact there is tool called Conere which allows you to drop tool results from context and became popular on twitter overnight on 1st day prompting its developer to increase its subscription price. Claude also subsequently released its own API for context management which allows passing instructions for dropping certain things from the context
  3. MCP is security mess - People have deleted/exposed their entire production database. Take an example - DB MCP exposes query tool to fire query, now LLM in its every-ready enthusiastic nature can fire a query which can harm you data integrity. Ideally you would all possible queries to be exposed as individual tool calls so you have control on query string but this is recommended in MCP. I get very anxious seeing Claude asking rm -fr bash permission. Ideally CC should never invoke rm -fr not even temporary directories. I have seen CC reading .env files and appending API keys to Authorisation headers when generating curl command either for testing or some quick fix. One can deny the permission but till that time CC (and Anthropic) already have your API Key in their logs.
  4. MCP is External - Typically you will 1-2 tools from 2-3 different MCPs. This requires you to add all MCPs and pay penalty for tools that you dont use. Also setup is manual.

What is the alternative?

Majority of MCP calls are actually API calls to Web Services. How do you invoke Web API call? Not through curl right? Most of time developers use sdk. Even when most web apis have released extensive documentation of their REST/Graphql APIs or OpenAPI files, api themselves always come with their own SDKs. So next question is what is a SDK? SDK is mostly TYPED request-responses, credential management, error handling, performance tweaks, async behaviour and few other non-functional goodies packaged together to be consumed from a program - not through CLI. AWS is an excellent example of API vs CLI - it has both. LLMs can not use SDKs directly even when they were trained on sdk calls and they already know how to use it. So how do you give a SDK to LLMs that is generic enough and extensible.

High Bandwidth Tools Call

Answer is - Code Generation + CLI. This combination powers LLM with high bandwidth communication with your tools. Command name and its arguments are less in tokens and tersest but most expressive form of tool invocation. Consider below hypothetical sequence of commands. LLM can plan and execute them reliably with error checking. If commands output meaningful error messages for LLM.

text
dynamic-cli myapi login
dynamic-cli myapi find_customer --customer-name="john doe"
dynamic-cli myapi find_customer_orders --cust_id=1214
dynamic-cli myapi update_order_status --order_id=1214 --status=shipped

Code Generation

LLMs core skill is generation. For SE focused tasks its Code Generation. They excel at it and can reliably generate correct code most of the time if given enough context. So why not use that ability? So I ended up creating an HTTP client that is extensible via LLMS ie. LLMs can generate code for request-response handling, credential management. This package - user prompt, generated code and local database together is presented to LLMs as command line executable, I call it as dynamic-cli

Dynamic CLI

I named this llm extension point as dynamic cli. It is written (vibe-coded) in Python and does following things.

  1. It allows add command and sub-commands through config file as well web interface
  2. Web Interface uses LLMs to generate request-response handlers. User has to enter exact description of how request is prepared and how response is handled
  3. CLI can generate correct --help output so that LLM can learn how to use CLI on its own.
  4. User can also add his personal set of commands in CLAUDE.md This is still a better solution than MCP because cli commands are concise and LLMs need not know all typing, credentials etc - only interface is CLI
  5. Through config, credentials are transparently passed to request/response handlers so they are never revealed or exposed. BTW, MCP also provides this capability so its not something MCP does not have.
  6. It works exactly like Claude Code ie. your project can have its own config file (./.dynamic-cli/config.json) and database. This allows you to checkin your config json in your git repo and tools will be available on every machine

Structure of Dynamic CLI is generic enough that one can use it to perform NON-HTTP work as well. When None is returned by Request handler, it is assumed that command does not call HTTP endpoint and you can perform non-http work in response handler.

MCP Interface

I have also included MCP interface for semantic search of commands. I have done this to check if I can maintain large set of tools in dynamic-cli config and retrieve them via semantic query through MCP and then ask LLM to compose correct command and execute it through BASH tool. I call this MCP mode. I wanted to find out If I can have agent which has access to large number of tools without paying cost of MCP tools metadata (through standard MCP) or not documenting all my dynamic-cli commands in Claude.md

How Do I use it?

I use it currently for Debugging my current development. When I am required to debug and ask CC, CC ends up firing multiple Curl requests, tailing logs etc. So I thought to give CC set of scripts to perform repetitive task. I ended up creating bunch of scripts which Claude happily consumed and ended adapting following format

  • Execute --help at the first time in new conversation. If script is already used before CC knows how to use it. But I can point it to scripts folder (through Claude.md) and based on my prompt CC can easily figure of rest of the things
  • Ask or through history - CC writes me script on its own. This was surprising behaviour - typically expected from decent developer but seeing this pattern implemented by CC on its own was serendipitous.

After few iterations, I decided to convert into a utility. It can hit my web services and retrieve logs and verify db entries - its as if writing a integration test on the fly. I personally feel this pattern is generic enough that one can use it to automate end-to-end tests.

Details about How to use it

Project-specific setup

Method 1: Use the initialization script (easiest)

bash
/path/to/dynamic-cli/bin/dynamic-cli-init
or for new project:
/path/to/dynamic-cli/bin/dynamic-cli-init my-new-project

Method 2: Manual setup Edit .dynamic-cli/config.json for project-specific commands

text
mkdir .dynamic-cli
cp /path/to/template/config.json .dynamic-cli/config.json

Starting the MCP Server (Admin UI)

Using the dedicated admin command. Make sure you have OpenAI API Key ENV Defined

bash
dynamic-cli-admin

Command Configuration

Project specific commands are stored at .dynamic-cli/config.json

json
{
  "name": "example",
  "help": "Example commands for this project",
  "subcommands": [
	{
	  "name": "hello",
	  "help": "Say hello",
	  "prepare_code": "def prepare(request, helpers):\n    return None  # Skip HTTP request",
	  "response_code": "def process_response(response, helpers):\n    return {\"message\": \"Hello from your project!\"}",
	  "arguments": [],
	  "request": {
		"method": "GET",
		"url": "https://httpbin.org/get",
		"headers": {},
		"query": {},
		"body": {
		  "mode": "json",
		  "template": {}
		},
		"response": {
		  "mode": "json",
		  "success_codes": [
			200
		  ]
		}
	  }
	}
  ]
}

Command arguments

Command arguments can directly mapped to Request bodies. Here tenant-id will be put into request body JSON. Helpers api also support path (URL Path Param), query(URL Query String), header, form locations. Command arguments are also available to prepare methods via Helpers API.

json
{
  "name": "tenant_id",
  "help": "Unique identifier for the tenant (alphanumeric, hyphens, underscores only)",
  "param_type": "option",
  "cli_name": "--tenant-id",
  "type": "str",
  "required": true,
  "location": "json",
  "target": "tenantId"
}

Script Environment

Following is an example of sample command database.query

Execute a SQL statement against the remote database API. The script injects credentials and ensures the payload matches the back-end requirements.

python
def prepare(request, helpers):
    headers = request.get("headers", {})
    headers.setdefault("apikey", helpers.secret("supabase_api_key"))
    headers.setdefault("Authorization", f"Bearer {helpers.secret('supabase_api_key')}")
    headers.setdefault("X-Client-Info", "dynamic-cli/1.0")
    request["headers"] = headers

    body = request.get("json", {})
    body.setdefault("project_id", helpers.secret("supabase_project_id"))
    body.setdefault("role", helpers.env("SUPABASE_ROLE", "service_role"))
    request["json"] = body
    return request


def process_response(response, helpers):
    if isinstance(response, dict) and "data" in response:
        return response["data"]
    return response

Inline scripts have access to a helpers object providing:

  • helpers.secret(name): Resolve configured secrets (env vars, files, commands, literal values)
  • helpers.env(name, default=None): Environment variable access
  • helpers.json(value): JSON serialization helper
  • helpers.state_set and helpers.state_get : To manage state (like Auth tokens, user_id etc) across command executions. This allows first command like login to save credentials or other state (like project-id) locally and which subsequent commands can read and use in their API requests.

Using Claude Code slash command

You can also write a slash command to generate config entries for your commands. Since you already have project context captured, Claude can effectively generate very handy commands configuration for you. Repository has sample command generation Prompt written which you can readily use to create slash command. You can generate elaborate and your use-case specific commands quickly.

Whats next

I have made dynamic-cli as powerful and rich like any other cli tools like Github gh or Supabase CLI. It took me weekend and one extra day to settle down on correct implementation and add other goodies. Next step for me now is to test this setup over tens of different command through MCP mode and find out if it works as designed. If you reading this line it means you definitely like the idea so give it try, here is repo URL - https://github.com/drutaTushar/cchttpclient. If you need any modifications or new features create an issue on github. I am sure there are bugs in it as its majorly vibe-coded but I have confirmed it that it works pretty good.