<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Yash Patil on Medium]]></title>
        <description><![CDATA[Stories by Yash Patil on Medium]]></description>
        <link>https://medium.com/@yash4421?source=rss-9dcfb449e244------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*JkwjnijFNPSr851OqEW7lw.jpeg</url>
            <title>Stories by Yash Patil on Medium</title>
            <link>https://medium.com/@yash4421?source=rss-9dcfb449e244------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 14:15:32 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@yash4421/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[From localhost to PyPI: Shipping a Real MCP Server (with a LangGraph Agent on Top)]]></title>
            <link>https://medium.com/@yash4421/from-localhost-to-pypi-shipping-a-real-mcp-server-with-a-langgraph-agent-on-top-37b70c91c098?source=rss-9dcfb449e244------2</link>
            <guid isPermaLink="false">https://medium.com/p/37b70c91c098</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[model-context-protocol]]></category>
            <category><![CDATA[langgraph]]></category>
            <category><![CDATA[mcp-server]]></category>
            <category><![CDATA[ai-agent]]></category>
            <dc:creator><![CDATA[Yash Patil]]></dc:creator>
            <pubDate>Mon, 25 May 2026 13:22:27 GMT</pubDate>
            <atom:updated>2026-05-25T13:22:27.259Z</atom:updated>
            <content:encoded><![CDATA[<h4>This is Part 3 of a 3-part series on the Model Context Protocol.</h4><ul><li><strong>Part 1 — </strong><a href="https://medium.com/@yash4421/what-is-mcp-the-model-context-protocol-explained-from-first-principles-4bb420536b93"><strong>What is MCP? The Model Context Protocol Explained from First Principles</strong></a></li><li><strong>Part 2 — </strong><a href="https://medium.com/@yash4421/build-an-mcp-server-in-python-stdio-http-and-the-mcp-inspector-c3af42c255a6"><strong>Build an MCP Server in Python: stdio, HTTP, and the MCP Inspector</strong></a></li><li><strong>Part 3 — From localhost to PyPI: Shipping a Real MCP Server (with a LangGraph Agent on Top)</strong> (you’re here)</li></ul><p>This is the part where things stop being a tutorial and start being a workflow.</p><p>In Part 1 you read the theory. In Part 2 you built two servers and learned to debug them. By the end of this post, you’ll have published an MCP server to PyPI so anyone in the world can install it with one command, wired that server into a real LangGraph agent that decides for itself which tools to call, plugged a community search MCP into the mix, put everything behind a single gateway, and shipped the whole thing in a Docker container.</p><p>Let’s start by packaging what we built.</p><h3>From folder to package</h3><p>The server we wrote in Part 2 was a single server.py file. That&#39;s fine for personal use, but to share it with the world we need to turn it into a proper Python package — pyproject.toml, src layout, entry points, the works.</p><p>Create a new folder outside Part 2’s directory:</p><pre>mkdir mcp-publish-tutorial<br>cd mcp-publish-tutorial<br>uv init<br>uv sync<br>source .venv/bin/activate<br>uv add fastmcp</pre><p>Then create this layout:</p><pre>mcp-publish-tutorial/<br>├── pyproject.toml<br>├── README.md<br>└── src/<br>    └── your_package_name/<br>        ├── __init__.py<br>        ├── main.py<br>        └── tools.py</pre><p>src/your_package_name/__init__.py is an empty file — it tells Python &quot;this is a package, not just a folder.&quot; <br>tools.py is where the actual tools live. main.py is the entry point that gets invoked when someone runs your package.</p><p>This is the “src layout” — the modern convention for Python packages. It prevents a category of import bugs (essentially, it makes sure you can’t accidentally import from the wrong place during development). If you’ve shipped Python packages before, you already know this. If not, just trust the layout for now.</p><p>A quick note on naming. There are three names you’ll juggle:</p><ul><li><strong>PyPI package name</strong> (the thing on pip install &lt;name&gt;)</li><li><strong>Python import name</strong> (what your code does from &lt;name&gt; import ...)</li><li><strong>CLI command</strong> (what users type to run it) — usually matches the PyPI name</li></ul><p>Keep these consistent and your life is easier. For this tutorial, my package name is agentic_terminal_yash — an MCP that gives an agent terminal capabilities. Yours will be different (PyPI names are globally unique). Use a placeholder in pyproject.toml for now; we&#39;ll fill in real names at the end.</p><h3>The tools: a real MCP server</h3><p>Open src/your_package_name/tools.py. Let&#39;s build something useful — a terminal-capability MCP with nine tools that let an LLM agent run shell commands, execute Python, find files, and manipulate the filesystem.</p><pre>from fastmcp import FastMCP<br>import subprocess<br>import os<br>import shutil<br>import glob as glob_lib<br>import re<br><br>mcp = FastMCP()<br><br><br>@mcp.tool()<br>def bash(command: str) -&gt; str:<br>    &quot;&quot;&quot;Executes a bash command and returns its stdout (or stderr on failure).<br><br>    Use this for any shell operation: listing directories, running CLIs,<br>    checking system state, running scripts. Returns the command&#39;s output as a string.<br><br>    Args:<br>        command: The full bash command to run, e.g. &quot;pwd&quot; or &quot;ls -la /tmp&quot;.<br>    &quot;&quot;&quot;<br>    try:<br>        result = subprocess.run(<br>            command, shell=True, check=True,<br>            stdout=subprocess.PIPE, stderr=subprocess.PIPE,<br>        )<br>        return result.stdout.decode(&quot;utf-8&quot;)<br>    except subprocess.CalledProcessError as e:<br>        return e.stderr.decode(&quot;utf-8&quot;)<br><br><br>@mcp.tool()<br>def python_code(code: str) -&gt; str:<br>    &quot;&quot;&quot;Executes a Python code string and returns its stdout.<br><br>    Use this for one-off computations, quick scripts, math, or testing snippets.<br>    The code runs in a fresh Python subprocess — no shared state across calls.<br><br>    Args:<br>        code: A Python code string, e.g. &#39;print(2 + 2)&#39; or &#39;import math; print(math.pi)&#39;.<br>    &quot;&quot;&quot;<br>    try:<br>        result = subprocess.run(<br>            [&quot;python&quot;, &quot;-c&quot;, code], check=True,<br>            stdout=subprocess.PIPE, stderr=subprocess.PIPE,<br>        )<br>        return result.stdout.decode(&quot;utf-8&quot;)<br>    except subprocess.CalledProcessError as e:<br>        return e.stderr.decode(&quot;utf-8&quot;)<br><br><br>@mcp.tool()<br>def python_file(file: str) -&gt; str:<br>    &quot;&quot;&quot;Executes a Python file by path and returns its stdout.<br><br>    Use this when there&#39;s an existing .py file you need to run.<br><br>    Args:<br>        file: Absolute or relative path to a Python file.<br>    &quot;&quot;&quot;<br>    try:<br>        result = subprocess.run(<br>            [&quot;python&quot;, file], check=True,<br>            stdout=subprocess.PIPE, stderr=subprocess.PIPE,<br>        )<br>        return result.stdout.decode(&quot;utf-8&quot;)<br>    except subprocess.CalledProcessError as e:<br>        return e.stderr.decode(&quot;utf-8&quot;)<br><br><br>@mcp.tool()<br>def glob(pattern: str) -&gt; list[str]:<br>    &quot;&quot;&quot;Returns files matching a glob pattern.<br><br>    Use this to find files when you don&#39;t know the exact name. Supports<br>    standard glob syntax: &#39;*&#39; for any chars, &#39;**&#39; for recursive, &#39;?&#39; for one char.<br><br>    Args:<br>        pattern: A glob pattern, e.g. &#39;*.py&#39;, &#39;src/**/*.json&#39;, or &#39;data/file?.txt&#39;.<br>    &quot;&quot;&quot;<br>    return glob_lib.glob(pattern, recursive=True)<br><br><br>@mcp.tool()<br>def grep(pattern: str, file: str) -&gt; list[str]:<br>    &quot;&quot;&quot;Returns lines in a file that match a regex pattern.<br><br>    Use this to search inside a known file. For unknown files, use glob first.<br><br>    Args:<br>        pattern: A regex pattern, e.g. &#39;def \\w+&#39; or &#39;TODO:&#39;.<br>        file: Path to the file to search.<br>    &quot;&quot;&quot;<br>    try:<br>        with open(file, &quot;r&quot;) as f:<br>            return [line.rstrip() for line in f if re.search(pattern, line)]<br>    except Exception as e:<br>        return [f&quot;Error: {e}&quot;]<br><br><br>@mcp.tool()<br>def read_file(file: str) -&gt; str:<br>    &quot;&quot;&quot;Reads a file and returns its contents as a string.<br><br>    Use this when you need the full content of a file. For just matching lines,<br>    use grep. For listing files, use glob.<br><br>    Args:<br>        file: Path to the file to read.<br>    &quot;&quot;&quot;<br>    try:<br>        with open(file, &quot;r&quot;) as f:<br>            return f.read()<br>    except Exception as e:<br>        return f&quot;Error: {e}&quot;<br><br><br>@mcp.tool()<br>def write_file(file: str, content: str) -&gt; str:<br>    &quot;&quot;&quot;Writes content to a file, creating or overwriting it.<br><br>    Use this to create new files or replace existing ones. To append instead<br>    of overwriting, read the file first and concatenate.<br><br>    Args:<br>        file: Path to write to.<br>        content: The full content to write. Will replace any existing content.<br>    &quot;&quot;&quot;<br>    try:<br>        with open(file, &quot;w&quot;) as f:<br>            f.write(content)<br>        return f&quot;Wrote {len(content)} bytes to {file}.&quot;<br>    except Exception as e:<br>        return f&quot;Error: {e}&quot;<br><br><br>@mcp.tool()<br>def create_folder(folder: str) -&gt; str:<br>    &quot;&quot;&quot;Creates a folder. Returns a message indicating success or that it exists.<br><br>    Args:<br>        folder: Path of the folder to create. Intermediate folders will also be created.<br>    &quot;&quot;&quot;<br>    try:<br>        os.makedirs(folder)<br>        return f&quot;Folder &#39;{folder}&#39; created.&quot;<br>    except FileExistsError:<br>        return f&quot;Folder &#39;{folder}&#39; already exists.&quot;<br>    except Exception as e:<br>        return f&quot;Error: {e}&quot;<br><br><br>@mcp.tool()<br>def delete_folder(folder: str) -&gt; str:<br>    &quot;&quot;&quot;Deletes a folder and everything in it.<br><br>    Use carefully — this is irreversible.<br><br>    Args:<br>        folder: Path of the folder to delete.<br>    &quot;&quot;&quot;<br>    try:<br>        if os.path.exists(folder):<br>            shutil.rmtree(folder)<br>            return f&quot;Folder &#39;{folder}&#39; deleted.&quot;<br>        return f&quot;Folder &#39;{folder}&#39; does not exist.&quot;<br>    except Exception as e:<br>        return f&quot;Error: {e}&quot;</pre><p>That’s nine tools. Same @mcp.tool() pattern from Part 2, just more of it. Let me pull three out for a closer look — the rest follow the same shape.</p><h4>bash: power, with a caveat</h4><pre>@mcp.tool()<br>def bash(command: str) -&gt; str:<br>    &quot;&quot;&quot;Executes a bash command...&quot;&quot;&quot;<br>    result = subprocess.run(command, shell=True, ...)</pre><p>This is the most powerful tool in the package — and the most dangerous. Notice shell=True: it lets the LLM run arbitrary shell commands on your machine. If you ask the agent to &quot;clean up my home directory&quot; and it interprets that liberally, the bash tool will execute whatever shell command the LLM generates.</p><p>For a tutorial that runs on your own laptop, this is fine — you’re the user, the LLM is your assistant. For anything production, you’d want a sandbox (a Docker container or restricted shell), an allowlist of safe commands, or an explicit confirmation step before each invocation. The pattern is real; the production hardening is your problem.</p><p>This is also why docstrings matter so much. A well-scoped docstring like the one above frames the tool’s purpose tightly — the LLM is more likely to use bash for &quot;list files&quot; than for &quot;modify my git history&quot; because the docstring scopes the intent.</p><h4>glob: a different return shape</h4><pre>@mcp.tool()<br>def glob(pattern: str) -&gt; list[str]:<br>    &quot;&quot;&quot;Returns files matching a glob pattern...&quot;&quot;&quot;<br>    return glob_lib.glob(pattern, recursive=True)</pre><p>Two things worth noting. First, the return type is list[str], not dict or str. FastMCP handles that fine — your tools can return any JSON-serializable type. The LLM sees the list as a list when it reads the response.</p><p>Second, the docstring tells the LLM exactly <em>what kind of pattern</em> to pass. “Use *.py for Python files, **/*.json for recursive search.&quot; Without that, the LLM might pass a regex pattern (which won&#39;t work) or a Windows-style pattern (which won&#39;t match on Mac/Linux). Be specific about your input formats.</p><h4>write_file: multiple args, real mutation</h4><pre>@mcp.tool()<br>def write_file(file: str, content: str) -&gt; str:<br>    &quot;&quot;&quot;Writes content to a file, creating or overwriting it...&quot;&quot;&quot;</pre><p>Two parameters, both required. FastMCP generates an input schema with both fields, and the LLM understands it needs to provide both.</p><p>A pattern I’d recommend: for any tool that mutates state, the docstring should <em>explicitly call out the destructive behavior</em>. Compare “writes content to a file” (vague) with “creating or overwriting” (clear). When the LLM is about to nuke a config file, you want it to have read the docstring carefully.</p><p>The other six tools — python_code, python_file, grep, read_file, create_folder, delete_folder — follow the same pattern: clear docstring, one or two args, simple return type. Copy those, write your own.</p><h3>Wiring up the entry point</h3><p>Now main.py. This is what gets invoked when someone runs your package.</p><pre>from your_package_name.tools import mcp<br><br>def main():<br>    mcp.run(transport=&quot;stdio&quot;)<br><br>if __name__ == &quot;__main__&quot;:<br>    main()<br></pre><p>Five lines. Imports the tools, exposes a main() function, runs the server with stdio transport.</p><p>Now the pyproject.toml — the file that tells Python&#39;s tooling how to build and ship your package.</p><pre>[project]<br>name = &quot;your-mcp-server-name&quot;<br>version = &quot;0.1.0&quot;<br>description = &quot;An MCP that adds terminal capabilities to an agent.&quot;<br>readme = &quot;README.md&quot;<br>requires-python = &quot;&gt;=3.10&quot;<br>dependencies = [<br>    &quot;fastmcp&gt;=3.3.1&quot;,<br>]<br><br>[build-system]<br>requires = [&quot;setuptools&gt;=65.5.0&quot;, &quot;wheel&quot;]<br>build-backend = &quot;setuptools.build_meta&quot;<br><br>[tool.setuptools.packages.find]<br>where = [&quot;src&quot;]<br><br>[project.scripts]<br>your-mcp-server-name = &quot;your_package_name.main:main&quot;</pre><p>Three sections to understand:</p><p><strong>[build-system]</strong> tells uv (and pip) what tools to use to build your package. setuptools is the de facto standard; you almost never deviate from this.</p><p><strong>[tool.setuptools.packages.find]</strong> tells setuptools to look inside the src/ folder for packages. This is the magic that makes the src layout work.</p><p><strong>[project.scripts]</strong> is the magic that lets someone run your MCP from the command line. It maps the command name to a Python function. The format is command = &quot;module:function&quot; — here, the command runs main() from your_package_name.main.</p><p>A small pro tip: <strong>keep the package name and the script name the same</strong>. If your PyPI package is your-mcp-server-name, make the CLI command your-mcp-server-name too. That way, when someone wants to run your MCP, they type one name. Mismatching them forces users to remember &quot;the package is X but the command is Y&quot;, which is friction.</p><h3>Build and verify locally</h3><p>Let’s make sure it works before pushing to PyPI.</p><pre>uv build</pre><p>This creates a dist/ folder with two files: a .whl (wheel — the binary distribution) and a .tar.gz (sdist — the source distribution). PyPI uses both.</p><p>Install it locally into your venv:</p><pre>uv pip install dist/your_mcp_server_name-0.1.0-py3-none-any.whl</pre><p>Now create a quick test in a separate file (test.py, outside src/):</p><pre>from your_package_name.tools import mcp<br><br>mcp.run(transport=&quot;stdio&quot;)</pre><p>Run it. You should see the FastMCP startup message — same as Part 2, but now it’s coming from an installed package, not a local file. Your code is now a real Python package, indistinguishable from one downloaded off PyPI.</p><h3>uv publish: your code, in the world</h3><p>Register an account on <a href="https://pypi.org/">pypi.org</a>. In your account settings, create an API token. Then:</p><pre>export UV_PUBLISH_TOKEN=&quot;&lt;your-token&gt;&quot;<br>uv publish</pre><p>You’ll see:</p><pre>Publishing 2 files to https://upload.pypi.org/legacy/<br>Uploading your_mcp_server_name-0.1.0-py3-none-any.whl<br>Uploading your_mcp_server_name-0.1.0.tar.gz</pre><p>That’s it. Your package is on PyPI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8rvdSFG8130sqaCX" /></figure><p>For this tutorial, I published mine as agentic_terminal_yash — real package, real PyPI listing. Anyone reading this can install it with:</p><pre>pip install agentic_terminal_yash<br># or<br>uv add agentic_terminal_yash<br># or run it directly without installing<br>uvx agentic_terminal_yash</pre><p>The uvx form is especially nice — it downloads and runs the package without permanently installing it, the way npx works in Node land. Most modern MCP setups invoke their servers through uvx.</p><p>OK, code is in the world. Now let’s give it a brain.</p><h3>The LangGraph ReAct agent</h3><p>In Part 2 you wrote a LangChain client that listed tools. That client didn’t actually <em>use</em> the tools — it just printed their descriptions. The next step is wiring those tools into an agent: an LLM that decides which tool to call, calls it, reads the result, and decides what to do next.</p><p>We’ll use LangGraph’s create_react_agent, which implements the ReAct pattern — <em>reason, act, observe, repeat</em>. The agent gets a user prompt, decides if any tool would help, calls it, sees the result, and either responds or calls another tool.</p><p>Add a few more dependencies:</p><pre>uv add langgraph langchain-openai langchain-mcp-adapters python-dotenv</pre><p>You’ll need an OpenAI API key. Create a .env file in your project root:</p><pre>OPENAI_API_KEY=sk-...</pre><p>Now create agent.py:</p><pre>import asyncio<br>import os<br>import sys<br>import uuid<br><br>from dotenv import find_dotenv, load_dotenv<br>from langchain_core.messages import AIMessageChunk, ToolMessage<br>from langchain_mcp_adapters.client import MultiServerMCPClient<br>from langchain_openai import ChatOpenAI<br>from langgraph.checkpoint.memory import MemorySaver<br>from langgraph.prebuilt import create_react_agent<br><br>load_dotenv(find_dotenv())<br><br>SYSTEM_PROMPT = (<br>    &quot;You are a helpful assistant with terminal capabilities &quot;<br>    &quot;(bash, python execution, file operations). &quot;<br>    &quot;Pick the right tool for the user&#39;s request and explain results clearly.&quot;<br>)<br><br><br>def require_api_key():<br>    if not os.getenv(&quot;OPENAI_API_KEY&quot;):<br>        print(&quot;ERROR: OPENAI_API_KEY not found. Add it to your .env file.&quot;, file=sys.stderr)<br>        sys.exit(1)<br><br><br>async def stream_response(agent, prompt, thread_id):<br>    config = {&quot;configurable&quot;: {&quot;thread_id&quot;: thread_id}}<br>    inputs = {&quot;messages&quot;: [{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: prompt}]}<br><br>    print(&quot;\nAgent: &quot;, end=&quot;&quot;, flush=True)<br><br>    async for stream_mode, chunk in agent.astream(<br>        inputs, config=config, stream_mode=[&quot;updates&quot;, &quot;messages&quot;]<br>    ):<br>        if stream_mode == &quot;messages&quot;:<br>            message, _ = chunk<br>            if isinstance(message, AIMessageChunk) and message.content:<br>                print(message.content, end=&quot;&quot;, flush=True)<br><br>        elif stream_mode == &quot;updates&quot;:<br>            for node_name, node_output in chunk.items():<br>                for msg in node_output.get(&quot;messages&quot;, []):<br>                    if getattr(msg, &quot;tool_calls&quot;, None):<br>                        for call in msg.tool_calls:<br>                            print(f&quot;\n  [tool] {call[&#39;name&#39;]}({call[&#39;args&#39;]})&quot;, flush=True)<br>                    elif isinstance(msg, ToolMessage):<br>                        preview = str(msg.content)[:200].replace(&quot;\n&quot;, &quot; &quot;)<br>                        print(f&quot;\n  [result] {preview}&quot;, flush=True)<br><br>    print()<br><br><br>async def main():<br>    require_api_key()<br><br>    client = MultiServerMCPClient({<br>        &quot;terminal&quot;: {<br>            &quot;transport&quot;: &quot;stdio&quot;,<br>            &quot;command&quot;: &quot;uvx&quot;,<br>            &quot;args&quot;: [&quot;agentic_terminal_yash&quot;],<br>        }<br>    })<br><br>    tools = await client.get_tools()<br>    print(f&quot;Loaded {len(tools)} MCP tools: {&#39;, &#39;.join(t.name for t in tools)}&quot;)<br><br>    llm = ChatOpenAI(model=&quot;gpt-4o-mini&quot;, temperature=0)<br>    agent = create_react_agent(<br>        llm, tools,<br>        prompt=SYSTEM_PROMPT,<br>        checkpointer=MemorySaver(),<br>    )<br><br>    thread_id = str(uuid.uuid4())<br><br>    print(&quot;\nType a prompt (or &#39;exit&#39; to quit).&quot;)<br>    while True:<br>        try:<br>            prompt = input(&quot;\nYou: &quot;).strip()<br>        except (EOFError, KeyboardInterrupt):<br>            print(&quot;\nGoodbye!&quot;)<br>            break<br><br>        if not prompt or prompt.lower() in {&quot;exit&quot;, &quot;quit&quot;}:<br>            print(&quot;Goodbye!&quot;)<br>            break<br><br>        try:<br>            await stream_response(agent, prompt, thread_id)<br>        except Exception as e:<br>            print(f&quot;\n[error] {type(e).__name__}: {e}&quot;)<br><br><br>if __name__ == &quot;__main__&quot;:<br>    asyncio.run(main())</pre><p>That’s the agent. Let me unpack the parts that matter.</p><p><strong>The client config now uses </strong><strong>uvx</strong>, not a local file path. That single change is what makes this real: the agent loads tools from a published package, not from server.py sitting in your folder. The same code would work on any colleague&#39;s machine, anywhere — they just need uvx installed.</p><p><strong>create_react_agent</strong> is LangGraph&#39;s pre-built ReAct loop. You hand it an LLM, a list of tools, and a system prompt; it returns an agent that knows how to reason-act-observe. You could write this loop yourself, but you&#39;d just be reinventing what&#39;s already a clean primitive.</p><p><strong>MemorySaver</strong> as the checkpointer gives the agent conversation history. Without it, each prompt is a fresh conversation. With it, &quot;now create a file inside that folder&quot; knows what &quot;that folder&quot; refers to from the previous turn. The thread_id is what groups turns into a conversation.</p><p><strong>agent.astream(...)</strong> with stream_mode=[&quot;updates&quot;, &quot;messages&quot;] is the streaming bit. Two streams interleave: messages gives you the LLM tokens as they generate (so the response prints character-by-character, not all at once), and updates tells you which node fired — useful for printing [tool] bash({&#39;command&#39;: &#39;pwd&#39;}) when the agent decides to call a tool, and [result] /Users/you/projects when the tool returns.</p><p>Run it:</p><pre>python agent.py</pre><pre>Loaded 9 MCP tools: bash, python_code, python_file, glob, grep, read_file, write_file, create_folder, delete_folder<br><br>Type a prompt (or &#39;exit&#39; to quit).<br>You:</pre><p>Try a prompt the agent can answer without tools:</p><pre>You: What is the capital of France?<br><br>Agent: The capital of France is Paris.</pre><p>No [tool] line — the LLM answered directly. Good, the agent isn&#39;t reaching for tools when it doesn&#39;t need them.</p><p>Now try one that forces tool use:</p><pre>You: List all python files in this directory<br><br>Agent:<br>  [tool] glob({&#39;pattern&#39;: &#39;*.py&#39;})<br>  [result] [&#39;agent.py&#39;, &#39;test.py&#39;]<br>There are 2 Python files in the current directory: agent.py and test.py.</pre><p>The agent picked glob, called it with the right pattern, read the result, and turned it into a natural-language answer. That&#39;s the full ReAct loop in one prompt.</p><p>Now a multi-turn one to test memory:</p><pre>You: Create a folder named demo_output<br><br>Agent:<br>  [tool] create_folder({&#39;folder&#39;: &#39;demo_output&#39;})<br>  [result] Folder &#39;demo_output&#39; created.<br>The folder &#39;demo_output&#39; has been created successfully.<br><br>You: Now create a hello.txt inside it with the text &quot;Hi from MCP&quot;<br><br>Agent:<br>  [tool] write_file({&#39;file&#39;: &#39;demo_output/hello.txt&#39;, &#39;content&#39;: &#39;Hi from MCP&#39;})<br>  [result] Wrote 10 bytes to demo_output/hello.txt.<br>Done — hello.txt is created inside demo_output.</pre><p>Notice the second prompt didn’t say “inside demo_output&quot; — it said &quot;inside it&quot;. The agent understood &quot;it&quot; referred to the folder from the previous turn. That&#39;s MemorySaver doing its job.</p><p>This is the moment MCP pays off. You wrote 9 tools, published them, and now an LLM can use them to do real work. The agent decides what to call. You don’t.</p><h3>Now let’s not stop at one server</h3><p>Your agent uses tools from one server. But MCP’s whole point is that you can mix servers. Let me show you with the most-used community MCP: DuckDuckGo search.</p><p>There’s a published package called duckduckgo-mcp-server that exposes a search tool. To use it, add it to your client config:</p><pre>client = MultiServerMCPClient({<br>    &quot;terminal&quot;: {<br>        &quot;transport&quot;: &quot;stdio&quot;,<br>        &quot;command&quot;: &quot;uvx&quot;,<br>        &quot;args&quot;: [&quot;agentic_terminal_yash&quot;],<br>    },<br>    &quot;search&quot;: {<br>        &quot;transport&quot;: &quot;stdio&quot;,<br>        &quot;command&quot;: &quot;uvx&quot;,<br>        &quot;args&quot;: [&quot;duckduckgo-mcp-server&quot;],<br>    },<br>})</pre><p>That’s it. Run the agent and now client.get_tools() returns 10 tools: your 9 plus DuckDuckGo&#39;s search. The LLM can decide whether to look something up online, run a shell command, or both.</p><p>There’s also a growing ecosystem of hosted commercial MCPs — Tavily for search, Linear for project management, Stripe for payments, and many more. They work the same way; you just point your client at their URL with an API key in the headers.</p><h3>One gateway, many servers</h3><p>Two servers is fine. Ten servers is workable. Fifty servers means fifty entries in your client config, and your tools list becomes overwhelming for the LLM (research shows LLMs make worse tool-selection decisions when they have to pick from too many options).</p><p>The solution is a <em>gateway</em> — one MCP server that mounts other MCP servers underneath it. Your client connects to the gateway; the gateway proxies tool calls to whichever underlying server owns them.</p><p>Create a new folder gateway/ and inside it, gateway.py:</p><pre>from fastmcp import FastMCP<br><br>mcp = FastMCP()<br><br>@mcp.tool()<br>def fetch():<br>    &quot;&quot;&quot;Use this tool to fetch the data from the source.&quot;&quot;&quot;<br>    return {&quot;data&quot;: &quot;Hello MCP&quot;}<br><br>@mcp.tool()<br>def process(path: str):<br>    &quot;&quot;&quot;Use this tool to process the fetched data.&quot;&quot;&quot;<br>    return {&quot;processed_data&quot;: f&quot;Data has been processed at path: {path}&quot;}<br><br>mcp.mount(FastMCP.as_proxy({<br>    &quot;mcpServers&quot;: {<br>        &quot;ddg_mcp&quot;: {&quot;command&quot;: &quot;uvx&quot;, &quot;args&quot;: [&quot;duckduckgo-mcp-server&quot;]},<br>    }<br>}))<br>mcp.mount(FastMCP.as_proxy({<br>    &quot;mcpServers&quot;: {<br>        &quot;terminal&quot;: {&quot;command&quot;: &quot;uvx&quot;, &quot;args&quot;: [&quot;agentic_terminal_yash&quot;]},<br>    }<br>}))<br><br>if __name__ == &quot;__main__&quot;:<br>    mcp.run(transport=&quot;streamable-http&quot;, host=&quot;0.0.0.0&quot;, port=8060)</pre><p>The gateway has two native tools (fetch, process) and mounts two external servers (duckduckgo-mcp-server and agentic_terminal_yash). When a client connects, it sees all the tools — the gateway&#39;s own plus the mounted ones.</p><p>Run it:</p><pre>python gateway.py</pre><p>Now open the MCP Inspector (from Part 2) and point it at http://localhost:8060/mcp. You&#39;ll see all the tools — fetch and process from the gateway itself, search from DuckDuckGo, and all 9 terminal tools from agentic_terminal_yash. One endpoint, many capabilities.</p><p>For your agent client, you now connect to just one URL instead of multiple commands:</p><pre>client = MultiServerMCPClient({<br>    &quot;gateway&quot;: {<br>        &quot;transport&quot;: &quot;streamable-http&quot;,<br>        &quot;url&quot;: &quot;http://localhost:8060/mcp&quot;,<br>    }<br>})</pre><p>Add a new MCP later, you don’t touch the agent code. You just add another mount call in the gateway. This is how MCP scales in real organizations.</p><h3>Docker: ship the gateway</h3><p>Local is fine for development. To deploy the gateway to a cloud platform — AWS, GCP, Fly.io, anywhere — you want it in a container.</p><p>In your gateway/ folder, create a Dockerfile:</p><pre>FROM python:3.11-slim<br><br># Install uv (which gives us uvx for free)<br>COPY --from=ghcr.io/astral-sh/uv:latest /uv /uvx /bin/<br><br>WORKDIR /app<br><br># Pre-install the MCP servers we&#39;ll proxy.<br># This avoids uvx having to download them on first request.<br>RUN uv tool install duckduckgo-mcp-server<br>RUN uv tool install agentic_terminal_yash<br><br># Install FastMCP for the gateway itself<br>RUN pip install fastmcp<br><br># Copy the gateway code<br>COPY . .<br><br># Make sure uv&#39;s tool installs are on PATH<br>ENV PATH=&quot;/root/.local/bin:${PATH}&quot;<br><br>CMD [&quot;python&quot;, &quot;-u&quot;, &quot;gateway.py&quot;]</pre><p>Build it:</p><pre>docker build -t mcp-gateway .</pre><p>Run it:</p><pre>docker run -d -p 8060:8060 --name mcp-container mcp-gateway</pre><p>Verify:</p><pre>docker ps</pre><pre>CONTAINER ID   IMAGE         COMMAND                  STATUS         PORTS                    NAMES<br>e5a335763c2c   mcp-gateway   &quot;python -u gateway.py&quot;   Up 2 seconds   0.0.0.0:8060-&gt;8060/tcp   mcp-container</pre><p>Your MCP gateway is now a containerized service. It’s portable — push the image to Docker Hub or GHCR, pull it onto any cloud VM, and your team has shared access to your MCP infrastructure.</p><p>Point the MCP Inspector at http://localhost:8060/mcp and you&#39;ll see the same tools you saw before, but now they&#39;re served from inside a container. Production-shape.</p><h3>What you built</h3><p>If you followed every part of this series, you now have:</p><ul><li><strong>Conceptual fluency</strong> with MCP — Part 1</li><li><strong>A working stdio server, an HTTP server, and two ways to connect to them</strong> — Part 2</li><li><strong>A published Python package on PyPI</strong> that anyone in the world can install</li><li><strong>A real LangGraph ReAct agent</strong> that decides which of your tools to call</li><li><strong>A gateway pattern</strong> for combining multiple MCP servers behind one endpoint</li><li><strong>A Dockerized deployment</strong> ready to ship to any cloud</li></ul><p>You also have a mental model — and that’s the thing that lasts. The protocol will evolve, the SDKs will change, FastMCP will hit a new major version, but the <em>idea</em> of “one standardized protocol between AI applications and tools” is here to stay. The skills you built across these three posts transfer cleanly.</p><p>A few things I didn’t cover that you might want to explore next:</p><ul><li><strong>MCP resources and prompts.</strong> I focused on tools (which is what 99% of MCP servers use), but the spec also defines resources (read-only data) and prompts (templates). If your use case fits, they’re worth a look.</li><li><strong>Authentication for production gateways.</strong> Streamable HTTP supports bearer tokens, API keys, OAuth — the MCP Inspector lets you configure headers, and the spec includes proper auth flows.</li><li><strong>Observability.</strong> Once your MCP is doing real work, you’ll want logs and metrics. LangSmith handles the agent side; FastMCP has its own logging hooks for the server side.</li></ul><p>That’s where the series ends. If it helped, the best thing you can do is build something with what you learned and share it — that’s how an ecosystem grows.</p><p>See you in whatever you ship next.</p><p><em>If this series helped, claps on any of the three parts make Medium show them to more people. Questions, weird errors, things I got wrong, drop them in the responses.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=37b70c91c098" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build an MCP Server in Python: stdio, HTTP, and the MCP Inspector]]></title>
            <link>https://medium.com/@yash4421/build-an-mcp-server-in-python-stdio-http-and-the-mcp-inspector-c3af42c255a6?source=rss-9dcfb449e244------2</link>
            <guid isPermaLink="false">https://medium.com/p/c3af42c255a6</guid>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[model-context-protocol]]></category>
            <category><![CDATA[mcp-server]]></category>
            <dc:creator><![CDATA[Yash Patil]]></dc:creator>
            <pubDate>Fri, 22 May 2026 13:59:03 GMT</pubDate>
            <atom:updated>2026-05-25T13:51:45.297Z</atom:updated>
            <content:encoded><![CDATA[<p><em>This is Part 2 of a 3-part series on the Model Context Protocol.</em></p><ul><li><strong>Part 1 — </strong><a href="https://medium.com/@yash4421/what-is-mcp-the-model-context-protocol-explained-from-first-principles-4bb420536b93"><strong>What is MCP? The Model Context Protocol Explained from First Principles</strong></a></li><li><strong>Part 2 — Build an MCP Server in Python: stdio, HTTP, and the MCP Inspector</strong> (you’re here)</li><li><strong>Part 3 — </strong><a href="https://medium.com/@yash4421/from-localhost-to-pypi-shipping-a-real-mcp-server-with-a-langgraph-agent-on-top-37b70c91c098"><strong>Ship It: Publishing MCP Servers to PyPI and Running Them in Docker</strong></a></li></ul><p>Part 1 was theory. Now we build.</p><p>By the end of this post you’ll have written two MCP servers — one stdio, one HTTP — connected to both with raw Python and with LangChain, and learned to debug them with the official MCP Inspector. About 70 lines of code total.</p><p>I’ll keep the explanations short and the code blocks honest. No mystery imports, no hidden config. If a line is there, you’ll know why.</p><p>Let’s set up.</p><h3>Setup</h3><p>You need Python 3.10 or later. We’re using uv, Astral&#39;s Python package manager that handles virtual environments, dependency resolution, and Python versions in one tool. If you&#39;re still using pip + venv, switching is worth it — uv is roughly an order of magnitude faster and the ergonomics are kinder.</p><pre>pip install uv<br>uv init mcp-tutorial<br>cd mcp-tutorial<br>uv sync<br>source .venv/bin/activate<br>uv add fastmcp mcp<br>uv add langchain langchain-mcp-adapters</pre><p>Then create a folder for your first server:</p><pre>mkdir 01_stdio<br>cd 01_stdio</pre><p>The directory layout we’ll end up with looks like this:</p><pre>mcp-tutorial/<br>├── .venv/<br>├── pyproject.toml<br>└── 01_stdio/<br>    ├── server.py<br>    ├── client_raw.py<br>    └── client_langchain.py</pre><p>That’s the entire setup. No global installs, no config files to edit. Let’s write some code.</p><h3>Your first MCP server (stdio)</h3><p>Create server.py:</p><pre>from fastmcp import FastMCP<br><br>mcp = FastMCP()<br><br>@mcp.tool()<br>def fetch():<br>    &quot;&quot;&quot;Use this tool to fetch the data from the source.&quot;&quot;&quot;<br>    return {&quot;data&quot;: &quot;Hello MCP&quot;}<br><br>@mcp.tool()<br>def process(path: str):<br>    &quot;&quot;&quot;Use this tool to process the fetched data.&quot;&quot;&quot;<br>    return {&quot;processed_data&quot;: &quot;Data has been processed at path:&quot; + path}<br><br>if __name__ == &quot;__main__&quot;:<br>    mcp.run(transport=&quot;stdio&quot;)</pre><p>Twelve lines. That’s a working MCP server.</p><p>Three things are worth pausing on:</p><p><strong>The </strong><strong>@mcp.tool() decorator is the entire trick.</strong> It registers the function as a tool the client can discover and call. The function name becomes the tool name, the parameters become the tool&#39;s input schema, the return value gets serialized to JSON. Everything else FastMCP handles for you.</p><p><strong>The docstring isn’t decorative — it becomes the tool’s </strong><strong>description field.</strong> When an LLM decides whether to call a tool, the docstring is the primary thing it reads. Treat docstrings like product copy: clear, specific, written for the LLM as the audience. We&#39;ll revisit this at the end of the post with a much better example.</p><p><strong>The </strong><strong>transport=&quot;stdio&quot; argument</strong> tells FastMCP to read messages from standard input and write to standard output. That&#39;s how the client will talk to it. We&#39;ll change this one argument later to switch to HTTP — that&#39;s the magic of FastMCP&#39;s design.</p><p>Run it:</p><pre>python server.py</pre><p>You’ll see:</p><pre>[09:12:33] INFO  Starting MCP server &#39;FastMCP-0f90&#39; with transport &#39;stdio&#39;</pre><p>And then… nothing? Right. A stdio server doesn’t “serve” in the way you might expect. It’s not a process you connect to. The <em>client</em> will launch this script as a subprocess when it needs to talk to it. Kill the server with Ctrl+C for now; the client will start its own copy.</p><p>Don’t take my word for any of this. Let’s write a client and watch the wires.</p><h3>The raw client</h3><p>This client is intentionally low-level. You won’t use code like this in production — we’ll write a better one in the next section. But seeing the raw protocol once helps you understand what LangChain is doing for you.</p><p>Create client_raw.py:</p><pre>import asyncio<br>import os<br>from mcp import ClientSession, StdioServerParameters<br>from mcp.client.stdio import stdio_client<br><br>server_script = os.path.join(os.path.dirname(os.path.abspath(__file__)), &quot;server.py&quot;)<br><br>server_params = StdioServerParameters(<br>    command=&quot;python3&quot;,<br>    args=[server_script],<br>    env={},<br>)<br><br>async def main():<br>    async with stdio_client(server_params) as (read, write):<br>        async with ClientSession(read, write) as session:<br>            await session.initialize()<br><br>            tools = await session.list_tools()<br>            print(&quot;Available tools:&quot;, tools)<br><br>            result = await session.call_tool(&quot;process&quot;, arguments={&quot;path&quot;: &quot;/data/raw&quot;})<br>            print(&quot;Result:&quot;, result)<br><br>if __name__ == &quot;__main__&quot;:<br>    asyncio.run(main())</pre><p>What’s happening here:</p><ul><li><strong>StdioServerParameters</strong> tells the client what command to run to spawn the server. The client <em>launches</em> the server — it doesn&#39;t connect to a long-running process.</li><li><strong>stdio_client(...)</strong> opens the subprocess and gives back two streams: one to read from, one to write to.</li><li><strong>ClientSession</strong> wraps those streams in the MCP protocol — JSON-RPC 2.0 under the hood — so you can call methods like list_tools() and call_tool() instead of crafting messages by hand.</li><li><strong>session.initialize()</strong> is the handshake. Client and server exchange protocol versions and capabilities. Skip it and nothing works.</li></ul><p>Run it:</p><pre>python client_raw.py</pre><p>Output (trimmed for readability):</p><pre>[09:14:02] INFO  Starting MCP server &#39;FastMCP-0f90&#39; with transport &#39;stdio&#39;<br><br>Available tools: tools=[<br>  Tool(name=&#39;fetch&#39;,<br>       description=&#39;Use this tool to fetch the data from the source&#39;,<br>       inputSchema={...}),<br>  Tool(name=&#39;process&#39;,<br>       description=&#39;Use this tool to process the fetched data&#39;,<br>       inputSchema={&#39;properties&#39;: {&#39;path&#39;: {&#39;type&#39;: &#39;string&#39;}},<br>                    &#39;required&#39;: [&#39;path&#39;], ...})<br>]<br><br>Result: content=[TextContent(type=&#39;text&#39;, text=&#39;{&quot;processed_data&quot;:&quot;Data has been processed at path:/data/raw&quot;}&#39;)]<br>        structuredContent={&#39;processed_data&#39;: &#39;Data has been processed at path:/data/raw&#39;}<br>        isError=False</pre><p>Three things to notice:</p><ol><li>The server started automatically — you didn’t run it yourself.</li><li>Your docstrings showed up as description. That&#39;s exactly what the LLM will see when it&#39;s deciding which tool to use.</li><li>The return value came back twice: once as text content (a JSON string) and once as structured content (a parsed dict). MCP supports both, and clients can use whichever fits.</li></ol><p>That’s the protocol working. Now let’s write the client you’d actually use.</p><h3>The better way: a LangChain client</h3><p>In production, you’re almost never going to write raw ClientSession code. You&#39;re going to use a framework — and right now, that framework is most likely LangChain or LangGraph. Both ship a small adapter library called langchain-mcp-adapters that converts MCP tools into LangChain StructuredTool objects. Which means MCP tools and native LangChain tools can be mixed in the same agent without any glue code.</p><p>Create client_langchain.py:</p><pre>import asyncio<br>import os<br>from langchain_mcp_adapters.client import MultiServerMCPClient<br><br>venv_python = os.path.join(<br>    os.path.dirname(os.path.dirname(os.path.abspath(__file__))),<br>    &quot;.venv/bin/python3&quot;,<br>)<br><br>server_script = os.path.join(os.path.dirname(os.path.abspath(__file__)), &quot;server.py&quot;)<br><br>async def main():<br>    client = MultiServerMCPClient({<br>        &quot;fetch_mcp&quot;: {<br>            &quot;transport&quot;: &quot;stdio&quot;,<br>            &quot;command&quot;: venv_python,<br>            &quot;args&quot;: [server_script],<br>        }<br>    })<br><br>    tools = await client.get_tools()<br>    for tool in tools:<br>        print(tool.name, &quot;→&quot;, tool.description)<br><br>if __name__ == &quot;__main__&quot;:<br>    asyncio.run(main())</pre><p>This is the JSON config from Part 1 — the “USB-C cable” — but in dictionary form. Each key is a server name (yours to choose); each value tells the client how to connect to it.</p><p>Run it:</p><pre>python client_langchain.py</pre><p>Output:</p><pre>fetch → Use this tool to fetch the data from the source<br>process → Use this tool to process the fetched data</pre><p>Cleaner output. And these aren’t just printable strings — they’re StructuredTool objects ready to drop into a LangChain or LangGraph agent. We&#39;ll do exactly that in Part 3.</p><p>If you’ve used LangChain’s native @tool decorator before, this is the moment it should click. From the agent&#39;s perspective, it doesn&#39;t care whether a tool came from MCP or was defined locally. Same interface, same calling convention.</p><h3>Going beyond local: streamable HTTP</h3><p>Stdio is great for personal tools, but you can only have one client at a time and the server has to live on the same machine. To share an MCP server across users or services, you want streamable HTTP — the same kind of transport you’d use for any web API.</p><p>The good news: switching transports requires changing exactly one line in your server.</p><p>Create a new folder 02_http next to 01_stdio, copy server.py into it, and change the last line:</p><pre>if __name__ == &quot;__main__&quot;:<br>    mcp.run(transport=&quot;streamable-http&quot;, host=&quot;0.0.0.0&quot;, port=8050)</pre><p>That’s it. The tools didn’t change. The decorators didn’t change. The function bodies didn’t change. Run it:</p><pre>python server.py</pre><pre>[11:02:18] INFO  Starting MCP server &#39;FastMCP-ee88&#39; with transport &#39;streamable-http&#39; on http://0.0.0.0:8050/mcp<br>INFO:     Started server process [18566]<br>INFO:     Uvicorn running on http://0.0.0.0:8050 (Press CTRL+C to quit)</pre><p>Your server is now a proper HTTP service. If you visit http://localhost:8050/mcp in a browser you&#39;ll get a Not Acceptable error — that&#39;s expected. MCP servers don&#39;t speak browser. They speak JSON-RPC over HTTP with specific accept headers, which is why we need a way to test them that <em>doesn&#39;t</em> involve hand-crafting curl commands.</p><h3>The MCP Inspector</h3><p>The MCP Inspector is a web UI that connects to any MCP server — yours or someone else’s and lets you list tools, run them with arbitrary arguments, and see exactly what comes back. It’s the official debugging tool for MCP and ships as an npm package, which means you don’t install it permanently; you run it with npx.</p><p>With your HTTP server still running in one terminal, open another:</p><pre>npx @modelcontextprotocol/inspector</pre><p>You’ll see something like this:</p><pre>Starting MCP inspector...<br>Proxy server listening on 127.0.0.1:6277<br>Session token: 2d47408e2af9871c506bfd41d9s0a2c37415dc349e1563a115022109fe766c95<br>Open inspector with token pre-filled:<br>  http://localhost:6274/?MCP_PROXY_AUTH_TOKEN=2d47408e...<br><br>MCP Inspector is up and running at http://127.0.0.1:6274</pre><p>Click the pre-filled URL. The Inspector opens in your browser.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GSa1bzPOIFgcxnCDglxbMQ.png" /></figure><p>In the left sidebar:</p><ol><li>Set <strong>Transport Type</strong> to Streamable HTTP</li><li>Set <strong>URL</strong> to <a href="http://localhost:8050/mcp">http://localhost:8050/mcp</a></li><li>Click <strong>Connect</strong></li></ol><p>You’ll see a green “Connected” indicator.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7MKgipm1rkYJsX8eDLKN6w.png" /></figure><p>Click the <strong>Tools</strong> tab. Both of your tools show up with their descriptions — the docstrings you wrote earlier.</p><p>Click <strong>process</strong>, type mypath into the path field, click <strong>Run Tool</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lzJ8rFIPW466PxsK8WYO8w.png" /></figure><p>The Inspector becomes part of your muscle memory once you start writing real servers. Whenever a tool isn’t doing what you expect, you don’t dig through logs, you point the Inspector at it, run the tool with the exact arguments the LLM was sending, and see what happens. I’ve saved hours this way.</p><p>It also works on third-party MCP servers. Want to inspect what tools Stripe’s MCP server exposes? Point the Inspector at it. No need to read source code.</p><h3>One client, two servers</h3><p>Here’s the moment that makes MCP click: you don’t need a different client for each server. Add a second entry to the JSON config and you’re done.</p><p>Update client_langchain.py to point at both servers:</p><pre>async def main():<br>    client = MultiServerMCPClient({<br>        &quot;fetch_mcp_stdio&quot;: {<br>            &quot;transport&quot;: &quot;stdio&quot;,<br>            &quot;command&quot;: venv_python,<br>            &quot;args&quot;: [stdio_server_script],<br>        },<br>        &quot;fetch_mcp_http&quot;: {<br>            &quot;transport&quot;: &quot;streamable-http&quot;,<br>            &quot;url&quot;: &quot;http://localhost:8050/mcp&quot;,<br>        },<br>    })<br><br>    tools = await client.get_tools()<br>    for tool in tools:<br>        print(tool.name, &quot;→&quot;, tool.description)</pre><p>Run it with the HTTP server still running, and you’ll see four tools listed — fetch and process from the stdio server, fetch and process from the HTTP server. Same code, two transports, one client.</p><p>Add a third server later, you add a third entry. Add a tenth, you add a tenth. This is what “standardized protocol” actually buys you.</p><h3>A sidebar: writing tools the LLM can actually use</h3><p>Now that you’ve built a server and watched a client call it, let me come back to the docstring point I made earlier.</p><p>Your fetch and process tools work, but their docstrings are weak. <em>&quot;Use this tool to fetch the data from the source&quot;</em> tells the LLM nothing. What source? What data? When should it use this tool versus another one? An LLM looking at that description and a dozen others has nothing to choose with.</p><p>Here’s what a real tool looks like:</p><pre>from datetime import datetime<br>from zoneinfo import ZoneInfo<br><br>@mcp.tool()<br>def get_current_time(timezone: str) -&gt; dict:<br>    &quot;&quot;&quot;Returns the current local time in the given IANA timezone.<br><br>    Use this when the user asks &quot;what time is it in X&quot; or needs to<br>    compute a time difference between regions. Returns both ISO 8601<br>    format and a human-readable string.<br><br>    Args:<br>        timezone: An IANA timezone name. Examples: &quot;America/New_York&quot;,<br>                  &quot;Europe/London&quot;, &quot;Asia/Tokyo&quot;, &quot;UTC&quot;. Case-sensitive.<br>    &quot;&quot;&quot;<br>    tz = ZoneInfo(timezone)<br>    now = datetime.now(tz)<br>    return {<br>        &quot;timezone&quot;: str(tz),<br>        &quot;iso&quot;: now.isoformat(),<br>        &quot;human&quot;: now.strftime(&quot;%A, %B %d %Y at %I:%M %p %Z&quot;),<br>    }</pre><p>Compare the two docstrings as if you were the LLM. The new one tells you:</p><ul><li><strong>What the tool does</strong> (returns current local time)</li><li><strong>When to use it</strong> (“when the user asks ‘what time is it in X’”)</li><li><strong>What format you get back</strong> (both ISO 8601 and human-readable)</li><li><strong>What to pass in</strong> (IANA timezone names, with concrete examples)</li></ul><p>This isn’t optional polish. It’s the single biggest lever for whether your MCP tools actually get used correctly. When you’re writing the docstring, imagine the LLM has thirty other tools to choose from. Why should it pick yours? Tell it. Tell it specifically.</p><p>A pattern I’ve started using: write the docstring <em>first</em>, before the function body. If you can’t write a clear, specific docstring, the tool isn’t well-scoped yet. Go back and split it, or rename it, or merge it with another one. The docstring is a design tool, not documentation.</p><h3>What you built, and what’s next</h3><p>If you followed along, you now have:</p><ul><li>A stdio MCP server with two tools</li><li>An HTTP MCP server with the same two tools</li><li>A raw Python client (to see the protocol up close)</li><li>A LangChain client (to use in production)</li><li>A working MCP Inspector setup (to debug everything)</li><li>A mental model for what makes a tool’s docstring useful</li></ul><p>In Part 3 we go from local to shipped. We’ll:</p><ul><li>Package your server into a proper Python project and publish it to PyPI so anyone in the world can install it with uvx</li><li>Build a real LangGraph ReAct agent that uses your tools to decide what to do</li><li>Plug in community MCP servers like DuckDuckGo to see what the ecosystem already gives you for free</li><li>Combine multiple servers behind a single gateway</li><li>Ship the whole thing in Docker</li></ul><p>See you there.</p><blockquote>If this helped, a clap helps the next person find it. Questions, weird errors, things I got wrong, drop them in the responses.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c3af42c255a6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is MCP? The Model Context Protocol Explained from First Principles]]></title>
            <link>https://medium.com/@yash4421/what-is-mcp-the-model-context-protocol-explained-from-first-principles-4bb420536b93?source=rss-9dcfb449e244------2</link>
            <guid isPermaLink="false">https://medium.com/p/4bb420536b93</guid>
            <category><![CDATA[model-context-protocol]]></category>
            <category><![CDATA[mcp-server]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[ai-agent]]></category>
            <dc:creator><![CDATA[Yash Patil]]></dc:creator>
            <pubDate>Thu, 21 May 2026 09:04:25 GMT</pubDate>
            <atom:updated>2026-05-25T13:51:11.330Z</atom:updated>
            <content:encoded><![CDATA[<h4>This is Part 1 of a 3-part series on the Model Context Protocol.</h4><ul><li><strong>Part 1 — What is MCP?</strong> (you’re here)</li><li><strong>Part 2 — </strong><a href="https://medium.com/@yash4421/build-an-mcp-server-in-python-stdio-http-and-the-mcp-inspector-c3af42c255a6"><strong>Build an MCP Server in Python: stdio, HTTP, and the MCP Inspector</strong></a></li><li><strong>Part 3 — </strong><a href="https://medium.com/@yash4421/from-localhost-to-pypi-shipping-a-real-mcp-server-with-a-langgraph-agent-on-top-37b70c91c098"><strong>Ship It: Publishing MCP Servers to PyPI and Running Them in Docker</strong></a></li></ul><p>A few months ago I was wiring an AI agent into about a dozen tools — Slack, an internal data portal, GitHub, a SharePoint search, some Workday endpoints. Each one needed its own client code. Each one had its own auth quirks. And every time a vendor pushed a breaking change, something would silently rot in production until someone noticed the agent was returning stale data.</p><p>If you’ve built anything in the agentic AI space, you’ve felt this. It’s the kind of grunt work that makes you stop and ask: <em>who is going to maintain all of this in six months?</em></p><p>That question is exactly why MCP exists.</p><p>This is the first post in a 3-part series where I’ll take you from “I have no idea what MCP is” to “I’ve built one, published it to PyPI, wired it into an agent, and shipped it in Docker.” This part is the conceptual one. No code yet. Just the <em>why</em>. If you skip the why, the code in Part 2 will feel like ceremony.</p><p>Let’s start with what life looked like before MCP.</p><h3>Life before MCP</h3><p>Say you’re a Python developer. You want your application to talk to Oracle Database. Oracle exposes a bunch of REST endpoints — /v1/create, /v1/query, /v1/update, you know the drill.</p><p>You sit down and write client code. You handle auth (JWT, API keys, whatever). You write functions that hit each endpoint, parse the response, surface errors. Standard stuff.</p><p>Now your boss says: “Also integrate Azure Synapse.” Cool. You write <em>another</em> client. Different auth, different endpoints, different response shapes. More code to maintain.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VVtt25PZXlczijPU" /><figcaption>Life before MCP. Every new service meant a new client, new auth, new parsing logic. The three pain points are spelled out at the bottom.</figcaption></figure><p>This worked fine for years. APIs aren’t going anywhere — MCP doesn’t replace them. But three pain points have always lurked underneath:</p><ol><li><strong>API URLs change.</strong> Oracle decides v1/create is now v2/create. Your code breaks. Maybe their changelog warned you, maybe it didn&#39;t. Either way, <em>you</em> are the one fixing it.</li><li><strong>Response shapes change.</strong> The endpoint still exists, but now result is nested under data.payload.result instead of just result. Your parser falls over. You go read the new docs and update your client.</li><li><strong>Every new service is a new client.</strong> Oracle, Synapse, Snowflake, Postgres, that internal microservice your platform team built last quarter — each one is a fresh implementation. Different auth, different conventions, different error handling.</li></ol><p>For traditional software, this is annoying but manageable. You write the code once, deploy, move on.</p><p>For agentic AI, it’s a nightmare. A real agent might use 20 to 50 tools. Nobody on your team has time to monitor 50 changelogs and refactor 50 clients every quarter. The maintenance cost grows linearly with every integration you add, and at some point the agent itself becomes the smallest part of your codebase.</p><p>This is the gap MCP fills.</p><h3>The paradigm shift</h3><p>Here is the core idea: what if the API provider built a thin, standardized wrapper in front of their API, and <em>you</em> just connected to that?</p><p>Not an SDK. Not a library you import. A separate process — a server — that exposes the provider’s capabilities as <em>functions</em> (the spec calls them <em>tools</em>) in a format every client understands.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7VHt8VUKekXtqyRp" /><figcaption>The same setup, with MCP. You connect to a JSON config; the config knows about the servers; the servers know about the APIs. You stop caring about URL changes.</figcaption></figure><p>So Oracle ships an Oracle MCP server. Inside that server are functions: create_record, query_records, update_record. Each function is a thin wrapper around the corresponding API call. When the URL changes from v1/create to v2/create, Oracle updates the function. You do not have to do anything.</p><p>When you want to talk to Oracle, you don’t write client code anymore. You point your application at the Oracle MCP server, and you call its functions. When Azure ships their MCP server, you point at that too. Same shape, same protocol, same calling convention.</p><p>This is what the MCP spec calls a <em>standardized protocol</em>. The Anthropic team often compares it to USB-C: before USB-C, every device had its own cable. Now there is one port that works for everything.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7XGfD3bxzhY6ZRSD" /><figcaption>From Anthropic’s MCP documentation. The protocol sits in the middle; AI applications plug in from one side, data sources and tools from the other. One port, many cables.</figcaption></figure><p>You can think of MCP itself as the USB-C port. The little JSON config you’ll write to tell your client <em>which</em> servers to connect to is just you plugging cables into that port. (We’ll write that JSON in Part 2)</p><h4>A quick note: who actually builds MCP servers?</h4><p>In the perfect future, every API provider ships their own MCP server. Oracle would ship oracle-mcp-server, Azure would ship synapse-mcp-server, and we&#39;d all live happily ever after.</p><p>We are not in that future yet, but we’re getting closer. Today, MCP servers come from three places:</p><ul><li><strong>Vendors.</strong> Stripe, Cloudflare, Notion, Atlassian, GitHub and a growing list of others now ship official MCP servers for their own products.</li><li><strong>The community.</strong> A huge ecosystem of open-source MCP servers exists on PyPI and npm — for DuckDuckGo search, Postgres, file systems, you name it. We’ll use a couple of these in Part 2.</li><li><strong>You.</strong> A lot of MCP usage right now is internal. Companies build MCP servers in front of their <em>own</em> internal APIs so their AI teams can consume them without writing fresh clients every time. We’ll build one of these in Part 3.</li></ul><p>If you take one thing from this section: MCP isn’t waiting for the world to catch up. There are already hundreds of servers out there. You can plug into three or four of them by the end of this afternoon.</p><h3>The architecture: Host, Client, Server</h3><p>When you read MCP docs, you’ll see three terms thrown around. They sound similar enough that they’re easy to confuse, so let’s nail them down once.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Xdl4vKimtIJ8ZoZj" /><figcaption>The three roles. Host coordinates, Client connects, Server provides.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ikVvB-xy-vTbkVs_QB3phA.png" /></figure><p>Here’s a concrete mapping for the kind of stack we’ll build in Part 3:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*06Wsj90J4HOWW47IqY1LXg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9xYVdbYi9y2xcMqm" /></figure><p>That image is worth staring at for a moment. The MCP server is <em>literally</em> the protection wall between your code and the underlying API. Your code only ever talks to the server. The server’s functions know how to talk to the API. When the API changes, only the server’s functions need updating — and ideally, the person maintaining the server is the API vendor themselves, not you.</p><h3>Transport: how the client and server actually talk</h3><p>MCP defines two ways the client and server can communicate. You’ll pick one when you build your server. It’s a small choice with real consequences, so it’s worth understanding upfront.</p><p><strong>Stdio transport</strong> runs the server as a local process on your own machine. Your client launches the server as a subprocess and talks to it through standard input and standard output — the same pipes you’ve been using since your first print() statement.</p><p>This is what most MCP servers used in the early days. It is fast, it has zero network overhead, and it’s dead simple to set up. The catch: only one client can talk to one server at a time. If you want to share a server across users or services, stdio is a dead end.</p><p><strong>Streamable HTTP transport</strong> runs the server as a proper web service. Your client talks to it the same way you’d talk to any REST API: HTTP POST requests, optional Server-Sent Events for streaming, headers for auth (bearer tokens, API keys, OAuth, whatever you need).</p><p>This is what the spec recommends today for anything that needs to scale. If you’re building a tool that more than one person or process will use, you want streamable HTTP.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_STlAdbEzt3y2bKEmFr09w.png" /></figure><p>Rule of thumb: stdio for personal tools and quick experiments, streamable HTTP for anything production-shaped. We’ll build both in Part 2 so you can feel the difference.</p><h3>The data layer: JSON-RPC 2.0</h3><p>One more piece, and then we’re done with theory.</p><p>Whatever transport you pick — stdio or HTTP — the actual <em>messages</em> flying between client and server are always in the same format: <strong>JSON-RPC 2.0</strong> This is what the spec calls the data layer.</p><p>You don’t really need to think about it day-to-day. The SDK handles it for you. But it’s worth knowing what’s happening under the hood, because every “what tools do you have?” call, every tool invocation, every response, is just a structured JSON message with a method name, some parameters, and an ID.</p><p>If you’ve ever poked at the network tab while a web app does its thing, this will feel familiar. JSON-RPC is older than REST and arguably cleaner for this kind of request/response work. The MCP spec picked it because it’s simple, well-understood, and transport-agnostic. The exact same message format works whether you’re sending it over a Unix pipe or an HTTPS connection.</p><h3>Where we go from here</h3><p>If you’ve made it this far, here’s what should be sitting in your head:</p><ul><li><strong>The problem MCP solves:</strong> writing and maintaining client code for every API is brittle, and it does not scale to agentic AI.</li><li><strong>The fix:</strong> the API provider (or the community, or you) ships a server that wraps the API as a set of functions. You connect to the server. When the API changes, the server’s maintainer updates the functions, not you.</li><li><strong>The architecture:</strong> Host → Client → Server. The host is your AI app, the client is the connection, the server provides the tools.</li><li><strong>The two transports:</strong> stdio for local experiments, streamable HTTP for production.</li><li><strong>The data layer:</strong> JSON-RPC 2.0, handled for you by the SDK.</li></ul><p>In Part 2, we stop reading and start building. We’ll write our first MCP server in about 15 lines of Python, connect to it from a raw client, rewrite that client using LangChain (which is what you’ll actually reach for in production), then convert the same server to streamable HTTP and poke at it with the MCP Inspector — a debugging tool that has saved me more hours than I’d like to admit.</p><p>See you there.</p><blockquote>If this helped, a clap or a follow tells the algorithm to show Part 2 to people like you when it goes up. Questions, corrections, war stories drop them in the responses.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4bb420536b93" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simplifying Kubernetes Energy Monitoring with Kepler]]></title>
            <link>https://medium.com/@yash4421/simplifying-kubernetes-energy-monitoring-with-kepler-a6ece01b15d3?source=rss-9dcfb449e244------2</link>
            <guid isPermaLink="false">https://medium.com/p/a6ece01b15d3</guid>
            <category><![CDATA[sustanability]]></category>
            <category><![CDATA[green-computing]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[cncf]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Yash Patil]]></dc:creator>
            <pubDate>Fri, 30 Jan 2026 16:19:48 GMT</pubDate>
            <atom:updated>2026-01-31T07:32:08.471Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/807/1*dyEfh7v3nAi6F5eNfqWDeA.png" /></figure><p><strong>PART 1: FOUNDATIONAL CONCEPTS (Understanding the Basics)</strong><br>• Chapter 1: Cloud Native And Kubernetes Basics<br>• Chapter 2: Understanding Observability<br>• Chapter 3: eBPF — The Magic Behind Kepler<br>• Chapter 4: Prometheus and Metrics<br>• Chapter 5: Grafana Visualisation</p><p><strong>PART 2: KEPLER DEEP DIVE (Understanding the Technology)</strong><br>• Chapter 6: What is Kepler?<br>• Chapter 7: How Kepler Works (Architecture)<br>• Chapter 8: RAPL and Power Measurement<br>• Chapter 9: Power Models and Attribution</p><p><strong>PART 3: HANDS-ON DEMO (Building Everything from Scratch)</strong><br>• Chapter 10: Mac Setup Prerequisites<br>• Chapter 11: Creating Your Kubernetes Cluster<br>• Chapter 12: Installing Prometheus and Grafana<br>• Chapter 13: Deploying Kepler<br>• Chapter 14: Building Powerful Dashboards<br>• Chapter 15: Running Power Experiments</p><h3>Introduction</h3><p>As a developer, I’ve always been curious about the environmental impact of the software I build. Data centers consume approximately 1–2% of global electricity, and that number is growing rapidly. But here’s the problem: <strong>most of us have no idea how much energy our applications actually consume</strong>.</p><p>When I discovered <a href="https://sustainable-computing.io/">Kepler</a> (Kubernetes-based Efficient Power Level Exporter), a CNCF Sandbox project, I knew I had to learn more. This blog post documents my journey from knowing nothing about power monitoring to building a complete demo from scratch.</p><h3>The Problem: Flying Blind on Energy</h3><p>Before Kepler, if you wanted to know how much power your Kubernetes workloads consumed, you had limited options:</p><ol><li><strong>Server-level power meters</strong> — Tells the total server consumption, but not which applications use how much</li><li><strong>CPU percentage estimates</strong> — 50% CPU usage doesn’t mean 50% of power consumption</li><li><strong>Guesswork</strong> — Not exactly scientific</li></ol><p>This is like trying to reduce your household electricity bill without knowing which appliances use the most power. You need visibility before you can optimize.</p><h3>PART 1: FOUNDATIONAL CONCEPTS</h3><h4>Chapter 1: Cloud Native and Kubernetes Basics</h4><p>Before we can understand Kepler, we need to understand where its runs. Let’s build your foundation step by step.</p><p>What is “Cloud Native”?</p><ul><li><strong>Simple Definition</strong><br>Cloud Native means building and running applications that fully exploit the advantages of cloud computing. Instead of running one big application on one server, you break it into small pieces (microservices) that can run anywhere, scale automatically, and recover from failures.</li></ul><p>The Cloud Native Computing Foundation (CNCF) is the organization that manages open-source cloud native projects. Kubernetes, Prometheus, Kepler — they’re all CNCF projects.</p><h4>What Problem Does Kubernetes Solve?</h4><p>Imagine you’re running a food delivery app like Swiggy or Zomato(for international readers: think DoorDash or Uber Eats):</p><ul><li><strong>During lunch rush (12–2 PM)</strong>: You need 500 CPU cores and 1TB of memory to handle thousands of simultaneous orders</li><li><strong>At 3 AM</strong>: You only need 20 CPU cores, paying for 500 is wasting money</li><li><strong>If one instance crashes</strong>: Customer orders shouldn’t fail, traffic should automatically route to healthy instances</li><li>Deploying updates: Should happen without downtime</li></ul><p>Doing this manually is impossible. <strong>Kubernetes automates all of this.</strong></p><p>But wait, can’t cloud auto-scaling handle this?</p><p>Yes! AWS EC2 Auto Scaling, Azure VMSS, and serverless platforms like AWS Lambda all solve parts of this problem. So why do companies still choose Kubernetes?</p><ol><li><strong>No vendor lock-in</strong>: Your application runs identically on AWS, Azure, GCP, or your own data center. Switch providers without rewriting everything.</li><li><strong>Better resource efficiency</strong>: Kubernetes bin-packs containers tightly. You might run 50 microservices on resources that would otherwise need 50 separate VMs or Lambda functions.</li><li><strong>Unified ecosystem</strong>: Tools like Prometheus (monitoring), Istio (networking), and Kepler (power monitoring) work across any Kubernetes cluster, regardless of where it runs.</li><li><strong>Complex workload support</strong>: Stateful applications, batch jobs, ML training pipelines — Kubernetes handles workloads that don’t fit neatly into serverless models.</li></ol><p>Kubernetes isn’t always the right choice, serverless is simpler for event-driven, stateless workloads. But for complex, multi-service applications that need portability and fine-grained control, Kubernetes remains the industry standard.</p><h4><strong>Kubernetes Definition</strong></h4><p>Kubernetes (K8s) is a system that automatically runs, scales, and heals your containerized applications across many machines. Think of it as an autopilot for your applications — you tell it what you want, and it figures out how to make it happen.</p><h4>Essential Kubernetes Concepts</h4><ol><li><strong>Containers</strong></li></ol><p>A container is your application packaged with everything it needs to run — code, libraries, settings, dependencies. It’s like a shipping container: standardized, portable, and isolated.</p><p><strong>Real-world analogy: </strong>A container is like a lunchbox. It has everything you need for your meal, it’s portable, and what’s inside doesn’t mix with other lunchboxes.</p><p>2. <strong>Pods</strong></p><p>A Pod is the smallest deployable unit in Kubernetes. It wraps one or more containers that share storage and network. Usually, one pod = one container, but sometimes related containers live together.</p><p><strong>Real-world analogy: </strong>A pod is like an apartment. Containers are the rooms. They share the same address (IP), plumbing (storage), and live together.</p><p>3. <strong>Nodes</strong></p><p>A Node is a physical or virtual machine that runs pods. It has CPU, memory, and an operating system. Kubernetes manages a pool of nodes.</p><p><strong>Real-world analogy: </strong>A node is like an apartment building. It can host many apartments (pods).</p><p>4. <strong>Cluster</strong></p><p>A Cluster is a group of nodes managed by Kubernetes. You interact with the cluster, and Kubernetes decides which node runs which pod.</p><p><strong>Real-world analogy: </strong>A cluster is like a neighborhood of apartment buildings, all managed by one property management company (Kubernetes).</p><p>5. <strong>Namespace</strong></p><p>A Namespace is a virtual separation within a cluster. It lets you organize resources and set boundaries between teams or environments.</p><p><strong>Real-world analogy: </strong>Namespaces are like different companies renting space in the same office building. They share the building but have their own separate areas.</p><h4>Visual: How Everything Fits Together</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EFVRcDVySGtFj4YjKST19w.png" /></figure><h4>Why This Matters for Kepler</h4><p>Kepler measures power consumption at the <strong>Pod level</strong>. This is revolutionary because before Kepler, you could only measure power at the Node (server) level. You had no idea which application was consuming how much energy. Kepler gives you that granularity.</p><blockquote><strong>💡 Key Insight</strong></blockquote><blockquote>In a Kubernetes cluster, hundreds of pods from different applications share the same nodes. Without Kepler, you see: ‘Node 1 uses 200 watts.’ With Kepler, you see: ‘Pod frontend-api’ uses 45W, pod database uses 80W, pod cache uses 25W…’ This granularity changes everything for optimization.</blockquote><h4>Chapter 2: Understanding Observability</h4><p>Observability is about understanding what’s happening inside your systems. In cloud-native world, it has three pillars.</p><p><strong>The Three Pillars of Observability</strong></p><ol><li><strong>Metrics — Numbers Over Time</strong></li></ol><p>Metrics are numerical measurements collected at regular intervals. They tell you the state of your system.</p><ul><li>CPU usage: 75%</li><li>Memory used: 2.3 GB</li><li>Requests per second: 1,500</li><li><strong>Power consumption: 45 watts ← This is what Kepler adds!</strong></li></ul><p>2. <strong>Logs — Events That Happened</strong></p><p>Logs are text records of events in your system.</p><ul><li>“2026–01–15 14:32:05 — User John logged in”</li><li>“2026–01–15 14:32:10 — Payment failed: insufficient funds”</li><li>“2026–01–15 14:32:15 — Database connection established”</li></ul><p>3. <strong>Traces — Following a Request</strong></p><p>Traces follow a single request as it travels through multiple services. Like tracking a package through the postal system.</p><p><strong>Where Kepler Fits</strong></p><blockquote><strong>🔌 Kepler’s Unique Contribution</strong></blockquote><blockquote>Kepler adds a FOURTH dimension to observability: ENERGY METRICS. Before Kepler, we could see CPU/memory usage but had no idea about actual power consumption. Kepler exposes metrics like <strong>kepler_container_joules_total </strong>so you can see exactly how much energy each container uses in Joules.</blockquote><p><strong>Why Traditional Monitoring Falls Short</strong></p><p>Traditional monitoring tools tell you:<br>This pod is using 50% CPU.</p><p>But they can’t tell you:<br>This pod consumed 25 watt-hours today, costing ₹2.10 and producing 15g of CO2</p><p><strong>Why does CPU percentage not equal power?</strong> Because different types of CPU operations consume different amounts of energy. A CPU doing complex math burns more power than one waiting for network data, even at the same ‘usage’ percentage.</p><p><strong>What Kepler Enables</strong></p><p>1. <strong>Cost allocation: </strong>Charge teams for their actual energy usage, not just CPU time<br>2. <strong>Carbon tracking: </strong>Calculate CO2 emissions per application using regional carbon intensity<br>3. <strong>Optimization: </strong>Identify power-hungry applications and fix inefficient code<br>4. <strong>Sustainability reporting: </strong>Provide data for ESG (Environmental, Social, Governance) reports</p><h4>Chapter 3: eBPF — The Magic Behind Kepler</h4><p><strong>This is the most important foundational concept.</strong> eBPF is the technology that makes Kepler possible. Let’s understand it step by step.</p><p><strong>First: What is the Linux Kernel?<br></strong>The Linux kernel is the core of the operating system. It’s the software that talks directly to your hardware (CPU, memory, network cards, disk) and manages everything. It’s like the foundation of a building — everything else sits on top of it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X7mAN7QP4suCJBms8fUZjQ.png" /></figure><p><strong>The Problem eBPF Solves</strong></p><p>Traditionally, if you wanted to add custom functionality to the kernel (like measuring power per process), you had two bad options:</p><ol><li><strong>Modify the kernel source code: </strong>Takes days/months to get approved by Linux maintainers. Very risky — one bug can crash the entire system.</li><li><strong>Write a kernel module: </strong>Complex, can crash your system, and breaks every time the kernel updates. Requires deep expertise.</li></ol><blockquote><strong>💡 eBPF: The Game Changer</strong></blockquote><blockquote>eBPF (extended Berkeley Packet Filter) lets you run small, safe programs INSIDE the Linux kernel without modifying the kernel or loading risky modules. It’s like having a superpower to observe and modify how the kernel works, but in a completely safe sandbox that can’t crash your system.</blockquote><h4>How eBPF Works (Simple Explanation)</h4><ol><li><strong>Write a small program: </strong>Usually in C or using high-level tools</li><li><strong>Kernel verifies it: </strong>The kernel checks it won’t crash, won’t loop forever, won’t access forbidden memory</li><li><strong>Attach to a “hook”: </strong>Hooks are points in the kernel where events happen (like “when a process runs” or “when network packet arrives”)</li><li><strong>Program runs when triggered: </strong>It collects data or modifies behaviour, then sends results to user space</li></ol><p><strong>Real-World Analogy</strong></p><p>Imagine an airport (the kernel). Normally, only airport staff (kernel code) can access restricted areas like the control tower or baggage systems.</p><p>eBPF is like giving security-cleared inspectors (your programs) special access badges. They can:</p><ul><li>Observe everything happening in secure areas</li><li>Take measurements and report back</li><li>Can’t damage anything or access prohibited areas</li><li>If they try anything suspicious, they’re immediately ejected</li></ul><p><strong>How Kepler Uses eBPF</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bs4RWEfQgFZpDgMmU0P2lg.png" /></figure><p>This data, combined with actual power readings from hardware (RAPL — we’ll cover this next), lets Kepler calculate how much power each container is using. <strong>All with minimal overhead (&lt;1% CPU impact)!</strong></p><h4>Chapter 4: Prometheus &amp; Metrics</h4><p>Prometheus is the standard tool for collecting and storing metrics in the cloud-native world. Kepler exports its power data as Prometheus metrics, so understanding Prometheus is essential.</p><blockquote><strong>📊 What is Prometheus?</strong></blockquote><blockquote>Prometheus is an open-source monitoring system that collects numeric metrics from your applications, stores them in a time-series database, and lets you query them. It’s a CNCF graduated project (the highest maturity level) — the gold standard for Kubernetes monitoring.</blockquote><p><strong>How Prometheus Works</strong></p><p>Prometheus uses a “pull” model. Instead of applications pushing data to Prometheus, Prometheus actively scrapes (fetches) data from applications at regular intervals.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N2ts7F_MKZ0F2e5qfqFVJQ.png" /></figure><p><strong>What is a Prometheus Exporter?</strong></p><p>An exporter is a piece of software that collects metrics from somewhere and exposes them in Prometheus format. <strong>Kepler is an exporter!</strong> It collects power metrics and exposes them for Prometheus to scrape.</p><p><strong>Kepler’s Prometheus Metrics</strong></p><p>When you install Kepler, it exposes these metrics:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1jMzlosAQ5H_z8kLzNF-ig.png" /></figure><p><strong>PromQL: The Query Language</strong></p><p>Prometheus has its own query language called PromQL. Here are useful queries for Kepler:</p><ol><li><strong>Power consumption in Watts (rate of Joules):</strong></li></ol><p>sum(rate(kepler_container_joules_total[5m])) by (namespace)</p><p>2. <strong>Top 5 power-consuming pods:</strong></p><p>topk(5, sum(rate(kepler_container_joules_total[5m])) by (pod))</p><p>3. <strong>Node-level power:</strong></p><p>sum(rate(kepler_node_package_joules_total[5m]))</p><h4>Chapter 5: Grafana Visualization</h4><blockquote><strong>📈 What is Grafana?</strong></blockquote><blockquote>Grafana is an open-source visualization platform that creates beautiful dashboards from data sources like Prometheus. It turns raw numbers into charts, graphs, and alerts that humans can understand. Think of Prometheus as the database and Grafana as the reporting tool.</blockquote><p><strong>Why Grafana + Kepler is Powerful</strong></p><p>While Prometheus stores the data, Grafana makes it visual and actionable. With Kepler + Grafana, you can create dashboards showing:</p><ul><li>Real-time power consumption per pod/namespace</li><li>Historical trends (power usage over days/weeks)</li><li>Comparison between applications</li><li>Alerts when power exceeds thresholds</li><li>Carbon footprint estimates based on regional grid data</li></ul><h3><strong>PART 2: KEPLER DEEP DIVE</strong></h3><p><em>Understanding how Kepler actually works</em></p><h4>Chapter 6: What is Kepler?</h4><blockquote><strong>🛰️ Official Definition</strong></blockquote><blockquote>Kepler is a Prometheus exporter that measures energy consumption at the container, pod, VM, and process level by reading hardware sensors (like Intel RAPL) and attributing power based on resource utilization. When hardware sensors aren’t available (like in VMs), it uses machine learning models to estimate power.</blockquote><p><strong>The Problem Kepler Solves</strong></p><p>Before Kepler, measuring power in Kubernetes was nearly impossible:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XHOpGvTpwwoMWKvoD4Vk6g.png" /></figure><h4>Chapter 7: How Kepler Works (Architecture)</h4><p>Let’s understand Kepler’s architecture and how it calculates power.</p><p><strong>The Architecture Diagram</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/1*C8vOYUZd_7QxrfjCizHfbg.png" /></figure><p><strong>Step-by-Step: How Kepler Calculates Power</strong></p><p><strong>Step 1: Collect Resource Usage via eBPF<br></strong>Kepler’s eBPF program hooks into the kernel and tracks every process’s CPU cycles, instructions, cache usage. It maps each process ID (PID) to its Kubernetes container.</p><p><strong>Step 2: Read Actual Power from Hardware<br></strong>Simultaneously, Kepler reads real power consumption from hardware sensors like Intel RAPL (for CPU/DRAM), NVML (for NVIDIA GPUs), or uses ML models when sensors aren’t available.</p><p><strong>Step 3: Apply the Ratio Model<br>This is the key insight:</strong> Kepler uses a ratio-based attribution model.</p><pre>Container Power = (Container CPU Usage / Total CPU Usage) × Total <br>                                                            Hardware Power</pre><p><strong>Example: </strong>If total CPU power is 100W and container A used 30% of CPU cycles, container A is attributed 30W of CPU power.</p><p><strong>Step 4: Handle Idle Power</strong></p><p>Power splits into <strong>dynamic power</strong> (varies with load) and <strong>idle power</strong> (constant baseline). Kepler distributes idle power among all containers based on their ‘size’ (resource requests), following the Greenhouse Gas Protocol guidelines.</p><p><strong>Step 5: Export as Prometheus Metrics</strong></p><p>Finally, Kepler exposes all data as Prometheus metrics on port 9102. Prometheus scrapes these every 15–30 seconds, storing the time-series data.</p><p><strong>Chapter 8: RAPL &amp; Power Measurement</strong></p><p>RAPL is the primary power source for Kepler on Intel systems. Let’s understand it deeply.</p><blockquote><strong>⚡ What is RAPL?</strong></blockquote><blockquote>RAPL (Running Average Power Limit) is a feature in Intel processors (since 2011) that provides energy consumption data for different power domains. It’s accessed via special CPU registers or the Linux powercap interface at /sys/class/powercap/intel-rapl/</blockquote><p><strong>RAPL Power Domains</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mQlXn5VX0xmWu7RR1lpk6A.png" /></figure><p><strong>When RAPL Isn’t Available<br></strong>RAPL is <strong>not available</strong> in:</p><ul><li><strong>Cloud VMs: </strong>AWS, GCP, Azure don’t expose RAPL to guest VMs</li><li><strong>ARM processors: </strong>Apple M1/M2/M3, AWS Graviton don’t have RAPL</li><li><strong>Docker Desktop on Mac: </strong>Runs in a VM, no direct hardware access</li></ul><p>In these cases, Kepler uses <strong>pre-trained ML models</strong> to estimate power based on resource usage patterns. These models were trained on real hardware and can estimate within ~10–15% accuracy.</p><blockquote><strong>💻 For Our Demo on Mac</strong></blockquote><blockquote>Since Mac doesn’t expose RAPL (especially on M1/M2/M3), Kepler will use its ‘estimator’ mode with ML models. This is perfect for learning and demos! You’ll still see power metrics, they’re just estimated rather than measured. For production deployments with real measurements, you’d use bare-metal Linux servers</blockquote><h4>Chapter 9: Power Models &amp; Attribution</h4><p>Understanding how Kepler attributes power to containers is crucial for interpreting the metrics.</p><p><strong>The Ratio Power Model</strong></p><p>Kepler’s primary model is the <strong>Ratio Power Model</strong>. It’s simple but effective:</p><ol><li>Measure total hardware power (from RAPL or estimates)</li><li>Collect resource usage per process (from eBPF)</li><li>Calculate each container’s share: usage_ratio = container_usage / total_usage</li><li>Attribute power: container_power = usage_ratio × total_power</li></ol><p><strong>Dynamic vs Idle Power</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_wlTFVBG_mHHRyCLbTrAcg.png" /></figure><p>Following the <strong>Greenhouse Gas Protocol</strong>, Kepler distributes idle power among all processes proportionally to their ‘size’ (requested resources). This ensures fair allocation of the always-on infrastructure cost.</p><p><strong>Converting Power to Carbon</strong></p><p>To calculate carbon emissions from power:</p><p><strong>Carbon (gCO2) = Energy (kWh) × Grid Carbon Intensity (gCO2/kWh) <br>India’s grid carbon intensity: </strong>~700–800 gCO2/kWh (varies by region and time). Data available from electricitymaps.com or India’s Central Electricity Authority</p><h3><strong>PART 3: HANDS-ON DEMO</strong></h3><p><em>Building your complete Kepler demo from scratch on Mac</em></p><h4><strong>Chapter 10: Mac Setup Prerequisites</strong></h4><p>Starting with a fresh MacBook? Let’s install everything you need step by step.</p><blockquote><strong>🖥️ What You’ll Install</strong></blockquote><blockquote>1. Homebrew (Mac package manager) 2. Docker Desktop (container runtime) 3. kubectl (Kubernetes CLI) 4. Kind (Kubernetes in Docker) 5. Helm (Kubernetes package manager)</blockquote><p><strong>Step 1: Install Homebrew</strong></p><p>Homebrew is the package manager for macOS. Open Terminal (Cmd + Space, type ‘Terminal’) and run:</p><pre>/bin/bash -c &quot;$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)&quot;</pre><p>Follow the prompts. After installation, you may need to add Homebrew to your PATH (the installer will tell you the exact commands).</p><p><strong>Step 2: Install Docker Desktop</strong></p><pre>brew install --cask docker</pre><p>After installation, open Docker Desktop from Applications. Wait until the whale icon in the menu bar stops animating. This may take a minute on first launch. Also go to Settings &gt; Resources and allocate at least 4GB RAM and 2 CPUs.</p><p><strong>Step 3: Install kubectl</strong></p><pre>brew install kubectl</pre><p>kubectl is the Kubernetes command-line tool. You’ll use it to interact with your cluster.</p><p><strong>Step 4: Install Kind</strong></p><pre>brew install kind</pre><p>Kind (Kubernetes in Docker) creates a Kubernetes cluster inside Docker containers. Perfect for local development.</p><p><strong>Step 5: Install Helm</strong></p><pre>brew install helm</pre><p>Helm is the Kubernetes package manager. We’ll use it to install Prometheus, Grafana, and Kepler.</p><p><strong>Step 6: Verify All Installations</strong></p><pre># Run each command - all should show version numbers<br>docker --version<br>kubectl version --client<br>kind version<br>helm version</pre><p><strong>Chapter 11: Creating Your Kubernetes Cluster</strong></p><p>Now let’s create a local Kubernetes cluster using Kind.</p><p><strong>Step 1: Create Cluster Configuration<br></strong>First, create a configuration file. This enables port forwarding so we can access services:</p><pre># Create the config file<br>cat &gt; kind-config.yaml &lt;&lt; &#39;EOF&#39;<br>kind: Cluster<br>apiVersion: kind.x-k8s.io/v1alpha4<br>nodes:<br>- role: control-plane<br>  extraPortMappings:<br>  - containerPort: 30000<br>    hostPort: 30000<br>  - containerPort: 30001<br>    hostPort: 30001<br>EOF</pre><p><strong>Step 2: Create the cluster</strong></p><pre>kind create cluster --name kepler-demo --config kind-config.yaml</pre><p>This takes 2–3 minutes. You’ll see progress messages as Kind downloads images and creates the cluster.</p><p><strong>Step 3: Verify Cluster</strong></p><pre># Check cluster info<br>kubectl cluster-info<br><br># List nodes<br>kubectl get nodes<br><br># List all pods (system pods)<br>kubectl get pods -A</pre><p>You should see your node with status ‘Ready’ and several system pods running.</p><h4>Chapter 12: Installing Prometheus &amp; Grafana</h4><p>Now we install the monitoring stack that will collect and visualize Kepler’s metrics</p><p><strong>Step 1: Add Helm Repository</strong></p><pre># Add the Prometheus community charts<br>helm repo add prometheus-community https://prometheus-community.github.io/helm-charts<br>helm repo update</pre><p><strong>Step 2: Install kube-prometheus-stack</strong></p><p>This installs Prometheus, Grafana, and node-exporter together:</p><pre>helm install prometheus prometheus-community/kube-prometheus-stack \<br>  --namespace monitoring \<br>  --create-namespace \<br>  --set prometheus.prometheusSpec.serviceMonitorSelectorNilUsesHelmValues=false</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l9VwhrhfHP4JulSTi_zVnA.png" /></figure><p><strong>Step 3: Wait for Pods</strong></p><pre># Watch pods come up (press Ctrl+C when all show Running)<br>kubectl get pods -n monitoring -w</pre><p><strong>Chapter 13: Deploying Kepler</strong></p><p>Finally, we install Kepler itself!</p><p><strong>Step 1: Add Kepler Helm Repo</strong></p><pre>helm repo add kepler https://sustainable-computing-io.github.io/kepler-helm-chart<br>helm repo update</pre><p>You can see the latest version by using the following command:</p><pre>helm search repo kepler</pre><p><strong>Step 2: Install Kepler</strong></p><p>For Prometheus to be able to discover the metrics exported by Kepler, the serviceMonitor needs to be enabled and labeled with the release name of your Prometheus install. In our installation we called our kube-prometheus-stack install prometheus:</p><pre>helm install kepler kepler/kepler \<br>    --namespace kepler \<br>    --create-namespace \<br>    --set serviceMonitor.enabled=true \<br>    --set serviceMonitor.labels.release=prometheus \</pre><p><strong>Step 3: Test Kepler Metrics</strong></p><pre># Port-forward to access Kepler metrics<br>kubectl port-forward -n kepler svc/kepler 9102:9102 &amp;<br><br># Wait a moment, then test<br>sleep 3<br>curl -s http://localhost:9102/metrics | grep kepler | head -20</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k4HCkwdwT5mLX1W2q2RFnQ.png" /></figure><blockquote><strong>🎉 Success!</strong></blockquote><blockquote>If you see metrics starting with ‘kepler_’ in the output, congratulations — Kepler is working! You’re now collecting power metrics from your Kubernetes cluster.</blockquote><h4>Chapter 14: Building Power Dashboards with Kepler</h4><p>This chapter shows how to visualize Kubernetes power and energy metrics using <strong>Kepler + Prometheus + Grafana</strong>.</p><p><strong>Step 1: Access Grafana</strong></p><p>Port-forward Grafana from the monitoring namespace:</p><pre>kubectl port-forward -n monitoring svc/prometheus-grafana 3000:80</pre><p>Open in browser:</p><pre>http://localhost:3000</pre><p>Login: <br>Get the admin password using:</p><pre>kubectl --namespace monitoring get secrets prometheus-grafana \<br>  -o jsonpath=&quot;{.data.admin-password}&quot; | base64 -d ; echo</pre><p>Login with:</p><ul><li><strong>Username:</strong> admin</li><li><strong>Password:</strong> (output from command above)</li></ul><p><strong>Step 2: Verify / Add Prometheus Data Source</strong></p><p>When using kube-prometheus-stack, Grafana already provisions Prometheus.<br>Go to:</p><pre>Connections → Data sources → Prometheus</pre><p>Ensure:</p><ul><li><strong>Name:</strong> Prometheus</li><li><strong>Default:</strong> enabled</li><li>Prometheus server URL:</li></ul><pre>http://prometheus-kube-prometheus-prometheus.monitoring:9090</pre><p><strong>Step 3: Import Kepler Dashboard (JSON)</strong></p><p>Instead of using Grafana dashboard IDs (which caused datasource issues), import via <strong>JSON</strong>.</p><p>Import steps:<br>1. Grafana → Dashboards → Import<br>2. Click Upload JSON file<br>3. Paste the dashboard JSON(below)<br>4. Click Import</p><p><strong>Kepler Power &amp; Energy Dashboard (JSON)</strong></p><p>This dashboard is aligned with:</p><ul><li>ML-based estimation (kind / macOS)</li><li>Pod-level and namespace-level attribution</li><li>CPU &amp; memory stress experiments</li></ul><blockquote><strong><em>Important:</em></strong><em> This dashboard automatically uses the </em><strong><em>default Prometheus datasource</em></strong><em> (no manual panel edits needed).</em></blockquote><p>Dashboard JSON</p><pre>{<br>  &quot;uid&quot;: &quot;kepler-power-energy&quot;,<br>  &quot;title&quot;: &quot;Kubernetes Power &amp; Energy Monitoring (Kepler)&quot;,<br>  &quot;timezone&quot;: &quot;browser&quot;,<br>  &quot;schemaVersion&quot;: 38,<br>  &quot;version&quot;: 1,<br>  &quot;refresh&quot;: &quot;10s&quot;,<br>  &quot;panels&quot;: [<br>    {<br>      &quot;type&quot;: &quot;stat&quot;,<br>      &quot;title&quot;: &quot;Total Cluster Power (Watts)&quot;,<br>      &quot;datasource&quot;: { &quot;type&quot;: &quot;prometheus&quot; },<br>      &quot;targets&quot;: [<br>        {<br>          &quot;expr&quot;: &quot;sum(rate(kepler_node_package_joules_total[1m]))&quot;,<br>          &quot;refId&quot;: &quot;A&quot;<br>        }<br>      ],<br>      &quot;fieldConfig&quot;: {<br>        &quot;defaults&quot;: {<br>          &quot;unit&quot;: &quot;watt&quot;,<br>          &quot;color&quot;: { &quot;mode&quot;: &quot;thresholds&quot; },<br>          &quot;thresholds&quot;: {<br>            &quot;steps&quot;: [<br>              { &quot;color&quot;: &quot;green&quot;, &quot;value&quot;: null },<br>              { &quot;color&quot;: &quot;red&quot;, &quot;value&quot;: 150 }<br>            ]<br>          }<br>        }<br>      },<br>      &quot;gridPos&quot;: { &quot;x&quot;: 0, &quot;y&quot;: 0, &quot;w&quot;: 12, &quot;h&quot;: 6 }<br>    },<br>    {<br>      &quot;type&quot;: &quot;timeseries&quot;,<br>      &quot;title&quot;: &quot;Cluster Power Over Time (Watts)&quot;,<br>      &quot;datasource&quot;: { &quot;type&quot;: &quot;prometheus&quot; },<br>      &quot;targets&quot;: [<br>        {<br>          &quot;expr&quot;: &quot;sum(rate(kepler_node_package_joules_total[1m]))&quot;,<br>          &quot;refId&quot;: &quot;A&quot;<br>        }<br>      ],<br>      &quot;fieldConfig&quot;: { &quot;defaults&quot;: { &quot;unit&quot;: &quot;watt&quot; } },<br>      &quot;gridPos&quot;: { &quot;x&quot;: 12, &quot;y&quot;: 0, &quot;w&quot;: 12, &quot;h&quot;: 6 }<br>    },<br>    {<br>      &quot;type&quot;: &quot;timeseries&quot;,<br>      &quot;title&quot;: &quot;Node Power Baseline vs Spike (Watts)&quot;,<br>      &quot;datasource&quot;: { &quot;type&quot;: &quot;prometheus&quot; },<br>      &quot;targets&quot;: [<br>        {<br>          &quot;expr&quot;: &quot;rate(kepler_node_package_joules_total[1m])&quot;,<br>          &quot;refId&quot;: &quot;A&quot;<br>        }<br>      ],<br>      &quot;fieldConfig&quot;: { &quot;defaults&quot;: { &quot;unit&quot;: &quot;watt&quot; } },<br>      &quot;gridPos&quot;: { &quot;x&quot;: 0, &quot;y&quot;: 6, &quot;w&quot;: 24, &quot;h&quot;: 6 }<br>    },<br>    {<br>      &quot;type&quot;: &quot;barchart&quot;,<br>      &quot;title&quot;: &quot;Power by Namespace (Watts)&quot;,<br>      &quot;datasource&quot;: { &quot;type&quot;: &quot;prometheus&quot; },<br>      &quot;targets&quot;: [<br>        {<br>          &quot;expr&quot;: &quot;sum(rate(kepler_container_joules_total[5m])) by (container_namespace)&quot;,<br>          &quot;refId&quot;: &quot;A&quot;<br>        }<br>      ],<br>      &quot;fieldConfig&quot;: { &quot;defaults&quot;: { &quot;unit&quot;: &quot;watt&quot; } },<br>      &quot;gridPos&quot;: { &quot;x&quot;: 0, &quot;y&quot;: 12, &quot;w&quot;: 12, &quot;h&quot;: 7 }<br>    },<br>    {<br>      &quot;type&quot;: &quot;barchart&quot;,<br>      &quot;title&quot;: &quot;Power by Pod (Watts)&quot;,<br>      &quot;datasource&quot;: { &quot;type&quot;: &quot;prometheus&quot; },<br>      &quot;targets&quot;: [<br>        {<br>          &quot;expr&quot;: &quot;sum(rate(kepler_container_joules_total[5m])) by (pod)&quot;,<br>          &quot;refId&quot;: &quot;A&quot;<br>        }<br>      ],<br>      &quot;fieldConfig&quot;: { &quot;defaults&quot;: { &quot;unit&quot;: &quot;watt&quot; } },<br>      &quot;gridPos&quot;: { &quot;x&quot;: 12, &quot;y&quot;: 12, &quot;w&quot;: 12, &quot;h&quot;: 7 }<br>    },<br>    {<br>      &quot;type&quot;: &quot;table&quot;,<br>      &quot;title&quot;: &quot;Top 10 Power-Hungry Pods&quot;,<br>      &quot;datasource&quot;: { &quot;type&quot;: &quot;prometheus&quot; },<br>      &quot;targets&quot;: [<br>        {<br>          &quot;expr&quot;: &quot;topk(10, sum(rate(kepler_container_joules_total[5m])) by (pod, container_namespace))&quot;,<br>          &quot;refId&quot;: &quot;A&quot;<br>        }<br>      ],<br>      &quot;gridPos&quot;: { &quot;x&quot;: 0, &quot;y&quot;: 19, &quot;w&quot;: 24, &quot;h&quot;: 6 }<br>    },<br>    {<br>      &quot;type&quot;: &quot;timeseries&quot;,<br>      &quot;title&quot;: &quot;Energy Consumed per Pod (Joules)&quot;,<br>      &quot;datasource&quot;: { &quot;type&quot;: &quot;prometheus&quot; },<br>      &quot;targets&quot;: [<br>        {<br>          &quot;expr&quot;: &quot;sum(kepler_container_joules_total) by (container, pod)&quot;,<br>          &quot;refId&quot;: &quot;A&quot;<br>        }<br>      ],<br>      &quot;fieldConfig&quot;: { &quot;defaults&quot;: { &quot;unit&quot;: &quot;joule&quot; } },<br>      &quot;gridPos&quot;: { &quot;x&quot;: 0, &quot;y&quot;: 25, &quot;w&quot;: 24, &quot;h&quot;: 7 }<br>    }<br>  ]<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iiVnCH7UoAv6m9xUZSvr4w.png" /></figure><h4>Chapter 15: Running Power Experiments</h4><p>Now we generate workloads and observe real-time power changes.</p><p><strong>Experiment 1: CPU-Intensive Workload</strong></p><pre>kubectl run cpu-stress \<br>  --image=polinux/stress \<br>  --restart=Never \<br>  -- stress --cpu 4 --timeout 300s</pre><p><strong>Experiment 2: Memory-Intensive Workload</strong></p><pre>kubectl run mem-stress \<br>  --image=polinux/stress \<br>  --restart=Never \<br>  -- stress --vm 2 --vm-bytes 512M --timeout 300s</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0AyxaUXm0WpwNzq7JBYvMw.png" /></figure><p><strong>What to observe in Grafana</strong></p><ul><li><strong>Total Cluster Power</strong> increases (~10–15 W)</li><li><strong>cpu-stress</strong> appears in:<br>- Power by Pod<br>- Top Power-Hungry Pods</li><li>Energy curve slope increases for cpu-stress</li><li>Power by Namespace shows spike in default</li><li>Energy consumed per pod increases steadily</li></ul><p><strong>Experiment 3: Watch in Grafana (Key Observations)</strong></p><p>While stress tests are running, you should clearly see:</p><ul><li>cpu-stress pod consuming higher CPU-related power</li><li>mem-stress pod contributing additional memory energy</li><li>Total cluster power increasing and staying elevated</li><li>Energy (Joules) accumulating over time</li></ul><blockquote>Even on kind + macOS, Kepler’s ML-based power models accurately reflect workload-driven energy changes.</blockquote><h4>Cleanup</h4><p>Delete stress test pods:</p><pre>kubectl delete pod cpu-stress mem-stress --ignore-not-found</pre><p>(Optional) Delete cluster when completely done:</p><pre>kind delete cluster --name kepler-demo</pre><p><strong>Final Notes (Important for Readers)</strong></p><ul><li>On laptops, VMs, and cloud environments, Kepler uses <strong>ML-based power estimation</strong></li><li>Absolute watt values may vary</li><li>Relative changes and attribution are accurate and meaningful</li></ul><p><strong>Resources</strong></p><p>If you want to start your own Kepler journey, here are the resources I found most helpful:</p><ul><li><strong>Kepler Documentation</strong>: <a href="https://sustainable-computing.io/">https://sustainable-computing.io/</a></li><li><strong>Kepler GitHub</strong>: <a href="https://github.com/sustainable-computing-io/kepler">https://github.com/sustainable-computing-io/kepler</a></li><li><strong>CNCF TAG Environmental Sustainability</strong>: <a href="https://tag-env-sustainability.cncf.io/">https://tag-env-sustainability.cncf.io/</a></li><li><strong>eBPF Introduction</strong>: <a href="https://ebpf.io/what-is-ebpf/">https://ebpf.io/what-is-ebpf/</a></li></ul><h4>Conclusion</h4><p>The cloud-native community has an opportunity — and I’d argue a responsibility — to make computing more sustainable. Kepler is a crucial tool in that effort. It brings visibility to a problem that’s been invisible for too long.</p><p>If you’re interested in green computing, sustainability, or just curious about where your CPU cycles go, I encourage you to try Kepler. The setup takes less than an hour, and the insights are eye-opening.</p><p><strong>Let’s make our Kubernetes clusters greener, one pod at a time. 🌱</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a6ece01b15d3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Complete Guide: Using Kubernetes Secrets Store CSI Driver with HashiCorp Vault]]></title>
            <link>https://engineering.clearroute.io/complete-guide-using-kubernetes-secrets-store-csi-driver-with-hashicorp-vault-1a6d104e9e5b?source=rss-9dcfb449e244------2</link>
            <guid isPermaLink="false">https://medium.com/p/1a6d104e9e5b</guid>
            <category><![CDATA[secretmanager]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[hashicorp-vault]]></category>
            <category><![CDATA[secret-storage-csi]]></category>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[Yash Patil]]></dc:creator>
            <pubDate>Sat, 19 Apr 2025 09:10:02 GMT</pubDate>
            <atom:updated>2025-04-22T08:26:34.725Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lWac0kEvvCx1rbNSgJc8_Q.png" /></figure><p>In today’s cloud-native world, managing secrets securely in Kubernetes environments is a critical challenge for organizations. As applications scale and teams grow, ensuring that sensitive information like API keys, database credentials, and certificates remain protected becomes increasingly complex.</p><p>This comprehensive guide will walk you through understanding Kubernetes secrets, their limitations, and how to implement a more secure approach using the Secrets Store CSI Driver with HashiCorp Vault. By the end of this guide, you’ll have a production-ready setup that keeps your secrets out of Kubernetes etcd and safely stored in Vault.</p><h3><strong>What are Kubernetes Secrets ?</strong></h3><p>Kubernetes Secrets are objects designed to store sensitive information such as passwords, OAuth tokens, and SSH keys. By using Secrets, you avoid hardcoding confidential data in your application code, Pod specifications, or container images.</p><p>A typical Kubernetes Secret looks like this:</p><pre>apiVersion: v1<br>kind: Secret<br>metadata:<br>  name: db-credentials<br>type: Opaque<br>data:<br>  username: YWRtaW4=  # Base64 encoded &quot;admin&quot;<br>  password: cGFzc3dvcmQxMjM=  # Base64 encoded &quot;password123&quot;</pre><p>Kubernetes makes these secrets available to containers either as mounted volumes or as environment variables.</p><h3><strong>Traditional Challenges with Kubernetes Secrets</strong></h3><p>Despite being better than hardcoded credentials, native Kubernetes Secrets have several significant limitations:</p><ol><li><strong>Storage in etcd</strong>: By default, all Secrets are stored in the Kubernetes control plane’s etcd database in plaintext (base64 encoding is not encryption). If someone gains access to your etcd, they potentially have access to all your secrets.</li><li><strong>Limited Encryption</strong>: While Kubernetes supports encryption at rest for etcd, it requires additional configuration and key management.</li><li><strong>No Built-in Rotation</strong>: Kubernetes doesn’t provide native mechanisms for secret rotation or versioning.</li><li><strong>Access Control Limitations</strong>: RBAC for Secrets is relatively coarse-grained, making it difficult to implement granular access policies.</li><li><strong>No Audit Trail</strong>: There’s limited visibility into who accessed which secrets and when.</li></ol><h3><strong>Secret Management Options in Kubernetes</strong></h3><p>Several approaches have emerged to address these limitations:</p><ol><li><strong>Kubernetes Secrets with etcd Encryption</strong>: Enabling encryption for etcd improves security but still stores secrets within the cluster.</li><li><strong>External Secrets Operator</strong>: Syncs secrets from external stores into Kubernetes, but ultimately still creates copies in etcd.</li><li><strong>Sealed Secrets</strong>: Encrypts secrets before storing them in etcd, requiring proper key management.</li><li><strong>Vault Sidecar Injector</strong>: Uses Vault Agent to fetch secrets, but requires specific application code changes.</li><li><strong>Secrets Store CSI Driver</strong>: Mounts secrets directly from external providers as volumes, which is our focus in this guide.</li></ol><h3><strong>What is the Secrets Store CSI Driver?</strong></h3><p>The Secrets Store CSI (Container Storage Interface) Driver is a Kubernetes storage plugin that enables pods to mount secrets from external secret stores directly as volumes. This approach completely bypasses etcd storage, significantly improving security posture.</p><p>Key benefits include:</p><ul><li>Secrets never stored in Kubernetes etcd</li><li>Direct integration with enterprise-grade secret management solutions</li><li>Support for secret rotation and versioning</li><li>Fine-grained access control through external providers</li><li>Comprehensive audit capabilities</li></ul><h3>How Does the Secrets Store CSI Driver Work?</h3><p>The workflow operates as follows:</p><ol><li>A pod requests a volume mount from the CSI driver</li><li>The CSI driver communicates with the appropriate provider (in our case, HashiCorp Vault)</li><li>The provider authenticates and fetches the secrets</li><li>The secrets are mounted as a volume in the pod</li><li>The application reads secrets as files from the mounted volume</li></ol><p>This architecture creates a secure pipeline between your trusted secret vault and your applications without intermediate storage.</p><h3>Prerequisites</h3><ul><li>A running Kubernetes cluster</li><li>kubectl configured to access your cluster</li><li>Helm 3.x installed</li></ul><h3>Installing HashiCorp Vault</h3><p>HashiCorp Vault is a secrets management tool that provides secure storage, dynamic secrets, encryption as a service, and more. We’ll start by installing Vault on our Kubernetes cluster using Helm.</p><p>First, let’s add the HashiCorp Helm repository to our local Helm configuration:</p><pre># Add HashiCorp helm repository<br>helm repo add hashicorp https://helm.releases.hashicorp.com</pre><p>This command registers the official HashiCorp Helm repository, which contains the Vault chart.</p><pre>helm repo update</pre><p>This updates your local repository cache to ensure you’re getting the latest version of the chart.</p><pre># Create namespace for Vault<br>kubectl create namespace vault</pre><p>This creates a dedicated namespace called “vault” in your Kubernetes cluster, which helps organize resources and control access to Vault components.</p><pre># Install Vault with the CSI Provider enabled<br><br>helm install vault hashicorp/vault \<br>  --namespace vault \<br>  --set=&quot;server.dev.enabled=true&quot; \<br>  --set=&quot;server.dev.devRootToken=root&quot; \<br>  --set=&quot;csi.enabled=true&quot;</pre><p>This command deploys Vault to your cluster with the following settings:</p><ul><li>helm install vault hashicorp/vault: Installs the &quot;vault&quot; chart from the HashiCorp repository</li><li>--namespace vault: Places all resources in the &quot;vault&quot; namespace</li><li>--set &quot;server.dev.enabled=true&quot;: Enables development mode (NOT for production use)</li><li>--set &quot;server.dev.devRootToken=root&quot;: Sets a fixed root token for easy access (change this in production)</li><li>--set=&quot;csi.enabled=true&quot;: This enables the Vault CSI Provider</li></ul><p>Now, let’s verify that Vault is running properly:</p><pre>kubectl get pods -n vault</pre><p>This command lists all pods in the “vault” namespace. You should see at least one pod named “vault-0” with status “Running”. If it’s still in “ContainerCreating” status, wait a minute and try again.</p><p>This single command deploys both Vault and the CSI Provider, simplifying our setup. The provider will be installed as a DaemonSet, running on every node in your cluster. This ensures that any pod, regardless of which node it’s scheduled on, can mount secrets from Vault. This provider acts as a translator between the CSI Driver and Vault’s API.</p><p>If you want to verify the CSI Provider installation, you can run:</p><pre>kubectl get pods -n vault | grep csi-provider</pre><p>You should see one pod per node in your cluster, all in the “Running” state.</p><p>⚠️ Note: The development mode configuration we’re using is perfect for learning but NOT suitable for production environments. For production, you should configure proper storage, HA settings, and secure authentication methods.</p><h3>Configuring Vault</h3><p>Now we need to configure Vault to allow Kubernetes pods to authenticate with it. This involves setting up the Kubernetes authentication method in Vault.</p><p>First, let’s open a shell inside the Vault pod to interact with the Vault server:</p><pre>kubectl exec -it -n vault vault-0 -- /bin/sh</pre><p>Once inside the pod, set the root token as an environment variable:</p><pre># Set environment variable for root token<br>export VAULT_TOKEN=root</pre><p>This configures the Vault CLI to use our root token for authentication. In a production environment, you would use a more secure token.</p><p>Now, let’s enable the Kubernetes authentication method in Vault:</p><pre>vault auth enable kubernetes</pre><p>This command enables the Kubernetes auth method at the default path (“kubernetes”). This auth method allows Kubernetes service accounts to authenticate with Vault.</p><p>Next, we configure the Kubernetes auth method with details about our cluster:</p><pre>vault write auth/kubernetes/config \<br>  kubernetes_host=&quot;https://$KUBERNETES_PORT_443_TCP_ADDR:443&quot; \<br>  token_reviewer_jwt=&quot;$(cat /var/run/secrets/kubernetes.io/serviceaccount/token)&quot; \<br>  kubernetes_ca_cert=@/var/run/secrets/kubernetes.io/serviceaccount/ca.crt \<br>  issuer=&quot;https://kubernetes.default.svc.cluster.local&quot;</pre><p>Let’s break down what this command does:</p><ul><li>vault write auth/kubernetes/config: Writes configuration settings to the Kubernetes auth method</li><li>kubernetes_host=&quot;https://$KUBERNETES_PORT_443_TCP_ADDR:443&quot;: Specifies the Kubernetes API endpoint (automatically derived from environment variables)</li><li>token_reviewer_jwt=&quot;$(cat /var/run/secrets/kubernetes.io/serviceaccount/token)&quot;: Provides a token that Vault uses to validate service account tokens</li><li>kubernetes_ca_cert=@/var/run/secrets/kubernetes.io/serviceaccount/ca.crt: Provides the certificate authority to verify the Kubernetes API server</li><li>issuer=&quot;https://kubernetes.default.svc.cluster.local&quot;: Sets the expected issuer of service account tokens</li></ul><p>This configuration allows Vault to communicate with the Kubernetes API server for authenticating service accounts.</p><h3>Installing the Secrets Store CSI Driver</h3><p>The Secrets Store CSI Driver is the core component that enables pods to mount secrets directly from external secret stores. It implements the Container Storage Interface (CSI) standard, allowing it to integrate seamlessly with Kubernetes.</p><p>Let’s install the driver using Helm:</p><pre># Add the Secrets Store CSI Driver Helm repository<br>helm repo add secrets-store-csi-driver https://kubernetes-sigs.github.io/secrets-store-csi-driver/charts</pre><p>This adds the official repository for the Secrets Store CSI Driver to your Helm configuration.</p><pre>helm repo update</pre><p>This updates your local Helm cache to ensure you have access to the latest version of the chart.</p><pre>helm install csi-secrets-store secrets-store-csi-driver/secrets-store-csi-driver --namespace kube-system</pre><p>This command:</p><ul><li>helm install csi-secrets-store: Names the release &quot;csi-secrets-store&quot;</li><li>secrets-store-csi-driver/secrets-store-csi-driver: Specifies the chart to install</li><li>--namespace kube-system: Places the resources in the kube-system namespace, which is common for cluster-wide components</li></ul><p>Now, let’s verify that the driver is running correctly:</p><pre>kubectl get pods -n kube-system | grep csi-secrets-store</pre><h3>Creating and Managing Secrets in Vault</h3><p>Now that we have Vault running, let’s populate it with some example secrets and configure access policies. We’ll continue working inside the Vault pod where we set up authentication earlier.</p><p>Let’s create some example secrets for our application:</p><pre># Create example secrets<br>vault kv put secret/myapp/config \<br>  username=&quot;db-user&quot; \<br>  password=&quot;db-password-123&quot; \<br>  api_key=&quot;api-key-xyz&quot;</pre><p>This command:</p><ul><li>vault kv put secret/myapp/config: Creates or updates a secret at path &quot;secret/myapp/config&quot;</li></ul><p>The subsequent lines define key-value pairs for our secret:</p><ul><li>A database username: “db-user”</li><li>A database password: “db-password-123”</li><li>An API key: “api-key-xyz”</li></ul><p>In Vault, all access is governed by policies. Let’s create a policy that allows read-only access to our application secrets:</p><pre>vault policy write myapp-policy - &lt;&lt;EOF<br>path &quot;secret/data/myapp/*&quot; {<br>  capabilities = [&quot;read&quot;]<br>}<br>EOF</pre><p>This command:</p><ul><li>vault policy write myapp-policy: Creates a policy named &quot;myapp-policy&quot;</li><li>path &quot;secret/data/myapp/*&quot;: Defines the paths this policy applies to (note the &quot;data&quot; part in the path, which is how KV v2 internally structures data)</li><li>capabilities = [&quot;read&quot;]: Grants read-only access, preventing modifications to these secrets</li></ul><p>This policy follows the principle of least privilege, granting only the specific permissions our application needs.</p><h3>Configuring Kubernetes Authentication</h3><p>Now we need to create a bridge between Kubernetes and Vault authentication systems. We’ll create a service account for our application and configure Vault to trust it.</p><p>First, let’s create a Kubernetes service account and the necessary RBAC permissions. Save the following YAML to a file named service-account.yaml:</p><pre>apiVersion: v1<br>kind: ServiceAccount<br>metadata:<br>  name: myapp-sa<br>  namespace: default<br>---<br>apiVersion: rbac.authorization.k8s.io/v1<br>kind: ClusterRoleBinding<br>metadata:<br>  name: vault-tokenreview-binding<br>roleRef:<br>  apiGroup: rbac.authorization.k8s.io<br>  kind: ClusterRole<br>  name: system:auth-delegator<br>subjects:<br>  - kind: ServiceAccount<br>    name: myapp-sa<br>    namespace: default</pre><p>This YAML defines two resources:</p><ol><li>ServiceAccount: Named &quot;myapp-sa&quot; in the &quot;default&quot; namespace, which our application will use</li><li>ClusterRoleBinding: Grants the service account permission to validate tokens (needed by Vault for authentication)</li></ol><p>Let’s apply this configuration to create these resources:</p><pre>kubectl apply -f service-account.yaml</pre><p>Now, we need to configure Vault to trust this service account. Inside the Vault pod, run:</p><pre>vault write auth/kubernetes/role/myapp \<br>  bound_service_account_names=myapp-sa \<br>  bound_service_account_namespaces=default \<br>  policies=myapp-policy \<br>  ttl=1h</pre><p>This command:</p><ul><li>vault write auth/kubernetes/role/myapp: Creates an authentication role named &quot;myapp&quot;</li><li>bound_service_account_names=myapp-sa: Specifies which service account can use this role</li><li>bound_service_account_namespaces=default: Restricts the service account to the &quot;default&quot; namespace</li><li>policies=myapp-policy: Associates the previously created policy with this role</li><li>ttl=1h: Sets a 1-hour time-to-live for authenticated sessions</li></ul><p>With this configuration:</p><ol><li>When a pod using the “myapp-sa” service account requests authentication</li><li>Vault will verify its identity with the Kubernetes API</li><li>If valid, Vault grants access according to the “myapp-policy”</li><li>This access expires after 1 hour</li></ol><p>This completes the authentication setup between Kubernetes and Vault.</p><h3>Implementing the Solution</h3><p>Now we’re ready to bring everything together. We need to create two key resources:</p><ol><li>A SecretProviderClass that tells the CSI driver how to fetch secrets from Vault</li><li>A Pod that uses these secrets</li></ol><p>Let’s start with the SecretProviderClass. Save the following YAML to a file named secret-provider.yaml:</p><pre>apiVersion: secrets-store.csi.x-k8s.io/v1<br>kind: SecretProviderClass<br>metadata:<br>  name: vault-database-config<br>spec:<br>  provider: vault<br>  parameters:<br>    vaultAddress: &quot;http://vault.vault:8200&quot;<br>    roleName: &quot;myapp&quot;<br>    objects: |<br>      - objectName: &quot;db-creds&quot;<br>        secretPath: &quot;secret/data/myapp/config&quot;<br>        secretKey: &quot;username&quot;<br>      - objectName: &quot;db-password&quot;<br>        secretPath: &quot;secret/data/myapp/config&quot;<br>        secretKey: &quot;password&quot;<br>      - objectName: &quot;api-key&quot;<br>        secretPath: &quot;secret/data/myapp/config&quot;<br>        secretKey: &quot;api_key&quot;</pre><p>This resource:</p><ul><li>kind: SecretProviderClass: Creates a new resource of this custom type</li><li>metadata.name: vault-database-config: Names this resource for referencing later</li><li>spec.provider: vault: Specifies that we&#39;re using the Vault provider</li><li>parameters.vaultAddress: Points to our Vault service (using Kubernetes DNS)</li><li>parameters.roleName: &quot;myapp&quot;: References the authentication role we created in Vault</li><li>objects: Lists the secrets to fetch:</li><li>Each entry maps a file name (objectName) to a specific secret path and key in Vault</li><li>For example, the username value from our secret will be mounted as a file named “db-creds”</li></ul><p>Now, let’s create a test pod to demonstrate the secret mounting. Save this YAML as test-pod.yaml:</p><pre>apiVersion: v1<br>kind: Pod<br>metadata:<br>  name: test-app<br>spec:<br>  serviceAccountName: myapp-sa<br>  containers:<br>  - name: test-app<br>    image: nginx<br>    volumeMounts:<br>    - name: secrets-mount<br>      mountPath: &quot;/mnt/secrets&quot;<br>      readOnly: true<br>  volumes:<br>  - name: secrets-mount<br>    csi:<br>      driver: secrets-store.csi.k8s.io<br>      readOnly: true<br>      volumeAttributes:<br>        secretProviderClass: vault-database-config</pre><p>This pod definition:</p><ul><li>serviceAccountName: myapp-sa: Uses our previously created service account</li><li>Creates a container using the nginx image (just as an example)</li><li>volumeMounts: Configures where the secrets will appear inside the container.</li><li>mountPath: &quot;/mnt/secrets&quot;: Makes secrets available at this path</li><li>readOnly: true: Prevents the container from modifying the secrets</li><li>volumes: Defines the volume to mount</li><li>csi.driver: secrets-store.csi.k8s.io: Uses our CSI driver</li><li>volumeAttributes.secretProviderClass: vault-database-config: References our SecretProviderClass</li></ul><p>Apply both configuration files to create the resources:</p><pre>kubectl apply -f secret-provider.yaml<br>kubectl apply -f test-pod.yaml</pre><p>These commands create the SecretProviderClass and the test pod. When the pod starts, the CSI driver will:</p><ol><li>Use the service account token to authenticate with Vault</li><li>Fetch the specified secrets from Vault</li><li>Mount them as files at the specified path in the container</li></ol><p>This happens transparently to the application, which simply reads the files as needed.</p><h3>Testing and Verification</h3><p>Let’s verify that our implementation works correctly by checking the mounted secrets in our test pod.</p><p>First, check that the pod is running:</p><pre># Check if pod is running<br>kubectl get pod test-app</pre><p>This command should show the pod status as “Running”. If it shows “ContainerCreating” or an error status, wait a moment and try again.</p><p>Once the pod is running, let’s examine the secrets directory:</p><pre># List the mounted secrets directory<br>kubectl exec test-app -- ls -l /mnt/secrets</pre><p>This command executes the ls -l command inside the test-app pod, showing us the contents of the /mnt/secrets directory. You should see three files:</p><ul><li>db-creds (containing the username)</li><li>db-password (containing the password)</li><li>api-key (containing the API key)</li></ul><p>The output will show these files with their permissions, owner, and timestamp.</p><p>Now, let’s check the actual content of these files:</p><pre># View the username secret<br>kubectl exec test-app -- cat /mnt/secrets/db-creds</pre><p>This should output db-user, the username we stored in Vault.</p><pre># View the API key secret<br>kubectl exec test-app -- cat /mnt/secrets/api-key</pre><p>This should output api-key-xyz, the API key we stored in Vault.</p><p>You can also check the password:</p><pre># View the password secret<br>kubectl exec test-app -- cat /mnt/secrets/db-password</pre><p>This should output db-password-123, the password we stored in Vault.</p><p>If you see all these values correctly, congratulations! Your Secrets Store CSI Driver with HashiCorp Vault integration is working properly. The secrets are being fetched directly from Vault and mounted as files in your pod, without ever being stored in Kubernetes etcd.</p><h3>Conclusion</h3><p>Congratulations! You’ve successfully implemented the Kubernetes Secrets Store CSI Driver with HashiCorp Vault integration. This powerful combination provides several significant advantages over traditional Kubernetes secrets management:</p><ol><li><strong>Enhanced Security</strong>: Your secrets are never stored in Kubernetes etcd, dramatically reducing your attack surface. Secrets are fetched at runtime only, ensuring they stay in the external store until actually needed.</li><li><strong>Single Source of Truth</strong>: Vault serves as the centralized repository for all secrets, eliminating synchronization issues.</li><li><strong>Advanced Secret Management</strong>: You gain access to Vault’s advanced features like dynamic secrets generation, automatic rotation, and detailed audit logs.</li><li><strong>Fine-grained Access Control</strong>: Vault’s policy system allows for precise control over who can access which secrets.</li><li><strong>Simplified Secret Consumption</strong>: Applications can consume secrets just like any other file, without requiring special code or libraries.</li></ol><p>Through this implementation, you’ve created a more secure, scalable, and maintainable approach to secrets management in your Kubernetes environment.</p><h4>References</h4><ul><li><a href="https://secrets-store-csi-driver.sigs.k8s.io/introduction">https://secrets-store-csi-driver.sigs.k8s.io/introduction</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1a6d104e9e5b" width="1" height="1" alt=""><hr><p><a href="https://engineering.clearroute.io/complete-guide-using-kubernetes-secrets-store-csi-driver-with-hashicorp-vault-1a6d104e9e5b">Complete Guide: Using Kubernetes Secrets Store CSI Driver with HashiCorp Vault</a> was originally published in <a href="https://engineering.clearroute.io/">ClearRoute Engineering Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>