<?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 sunny mishra on Medium]]></title>
        <description><![CDATA[Stories by sunny mishra on Medium]]></description>
        <link>https://medium.com/@mishra.sunny?source=rss-4f2a0f316b56------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*PZ_oeXfH3I8hHTP1UIuuNQ.png</url>
            <title>Stories by sunny mishra on Medium</title>
            <link>https://medium.com/@mishra.sunny?source=rss-4f2a0f316b56------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 02:29:58 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mishra.sunny/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 Swim Meet PDFs to a Multi-Environment Cloud Run Platform]]></title>
            <link>https://medium.com/@mishra.sunny/from-swim-meet-pdfs-to-a-multi-environment-cloud-run-platform-71246631643c?source=rss-4f2a0f316b56------2</link>
            <guid isPermaLink="false">https://medium.com/p/71246631643c</guid>
            <category><![CDATA[streamlit]]></category>
            <category><![CDATA[pdf-parsing]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-visualization]]></category>
            <dc:creator><![CDATA[sunny mishra]]></dc:creator>
            <pubDate>Sun, 12 Apr 2026 01:23:48 GMT</pubDate>
            <atom:updated>2026-04-12T01:23:48.592Z</atom:updated>
            <content:encoded><![CDATA[<h3>Part 1: Start Simple, Solve the Real Pain</h3><p>If you’ve spent time around swim meets, you know the pattern. A meet ends, results get exported as a PDF, and that PDF becomes the official record: event name, swimmer, age, team, place, and time. For one quick lookup, that format works perfectly well. If I only want to check how Foo did in 50 Yard Freestyle, the PDF is enough.</p><p>That is the PDF’s strength, and also its limit.</p><p>The moment I want to ask a better question, the workflow starts breaking down. How has Foo improved in backstroke across a season? What does freestyle look like across ten meets? Which results were relays, and which were individual swims? Those are not hard analysis problems. They only feel hard because the data is locked inside documents built for reading, not querying.</p><p>That was the real starting point for this project. The goal was not a dashboard for its own sake. The goal was to remove the bottleneck between swim meet PDFs and actual swimmer analysis.</p><h4>The Problem</h4><p>A swim meet PDF is a good snapshot, but a poor database.</p><p>It works for questions like:</p><ul><li>What time did Foo swim in this event?</li><li>What place did Bar finish?</li><li>Which team was listed on this result sheet?</li></ul><p>It does not work well for questions like:</p><ul><li>How has one swimmer improved in a specific stroke over time?</li><li>Which events has a swimmer entered across many meets?</li><li>How do results vary across dates, teams, and event types?</li><li>Which entries are relay swims and which are individual swims?</li></ul><p>There is a second problem too: swim result PDFs do not all share the same structure.</p><p>One file might look like this:</p><p>Event 12 Girls 10 &amp; Under 50 Yard Freestyle 1 Foo, Maya 10 FAST 32.45 2 Bar, Lina 10 WAVE 33.10</p><p>Another might look like this:</p><p>Event #14 Boys 8 &amp; Under 25 Yard Backstroke 7.20 1 8 F Foo, Noah FST 7.55 2 8 F Bar, Eli WAV</p><p>A person can read both immediately. A parser should not assume both follow the same pattern. That is the real bottleneck: the information is there, but it is trapped inside inconsistent layouts.</p><h4>The Goals</h4><p>For the first version of the project, the goals were simple:</p><ol><li>Read swim meet PDFs programmatically.</li><li>Support multiple result layouts instead of assuming one fixed format.</li><li>Extract useful fields into one normalized CSV schema.</li><li>Validate the parsed output before updating the working dataset.</li><li>Build a Streamlit app on top of that CSV for search, filtering, and analysis.</li></ol><p>So Part 1 started as a data pipeline first, and a UI second.</p><h4>The Plan</h4><p>The architecture for this part is straightforward:</p><p>PDF -&gt; family detection -&gt; row extraction -&gt; CSV normalization -&gt; validation -&gt; safe write -&gt; Streamlit analysis</p><p>That pipeline became the backbone of the app.</p><h4>The Parser’s Job: Detect, Extract, Normalize</h4><p>The parser follows one rule: the PDFs may vary, but the output should not.</p><p>At the top of the parser, the target schema is defined as:</p><ul><li>Meet_Name</li><li>Meet_Date</li><li>Name</li><li>Age</li><li>Rank</li><li>Time</li><li>Team</li><li>Notes</li><li>Event_Type</li></ul><p>That matters because every supported PDF, no matter how different it looks, has to end up in the same shape. The parser is not trying to preserve the PDF’s layout. It is trying to preserve the meaning of the result.</p><p>Instead of building one giant parser for every file, the script first detects what kind of PDF it is handling. It looks for structural patterns such as:</p><ul><li>Event vs Event #</li><li>HY-TEK-style table headers</li><li>packed vs spaced-out tokens</li><li>relay row shapes vs individual row shapes</li></ul><p>Once it recognizes the pattern, it routes the file to a family-specific parsing adapter. That design keeps the logic practical and maintainable. The same swim data can arrive in several export shapes, and the parser handles that by classifying first and extracting second.</p><h4>Handling Multiple PDF Layout Families</h4><p>Take this structure:</p><p>Event 12 Girls 10 &amp; Under 50 Yard Freestyle 1 Foo, Maya 10 FAST 32.45 2 Bar, Lina 10 WAVE 33.10</p><p>Here the parser can cleanly identify:</p><ul><li>the event header</li><li>swimmer name</li><li>age</li><li>team</li><li>rank</li><li>time</li></ul><p>Now compare that with a tighter format:</p><p>Event #14 Boys 8 &amp; Under 25 Yard Backstroke 7.20 1 8 F Foo, Noah FST</p><p>The information is still there, but the parser has to infer more:</p><ul><li>which token is the time</li><li>which token is the rank</li><li>which token is the age</li><li>where the name begins</li><li>where the team token ends</li></ul><p>That is why the parser is organized by families. The real challenge is not reading PDF text. It is interpreting multiple layouts correctly and turning them into one normalized model.</p><h4>Turning Results Into One CSV Schema</h4><p>Once a row is extracted, the parser converts it into normalized CSV output.</p><p>A fictional result might look like this:</p><p>Meet_Name,Meet_Date,Name,Age,Rank,Time,Team,Notes,Event_Type Foo Invitational,1/12/2026,Maya Foo,10,1st,32.45,FAST,,Girls 10&amp;U 50 Yard Freestyle Foo Invitational,1/12/2026,Lina Bar,10,2nd,33.10,WAVE,,Girls 10&amp;U 50 Yard Freestyle Bar Winter Meet,2/02/2026,Noah Foo,8,1st,7.20,FST,,Boys 8&amp;U 25 Yard Backstroke</p><p>That transformation is the key moment in the project. Once the results live in CSV form, they can be filtered, grouped, charted, and searched. The PDF stops being the analysis layer. The CSV becomes the data layer.</p><h3>Implementation Details</h3><p>Part 1 is implemented as a small Python data pipeline.</p><p>The parser:</p><ul><li>reads one PDF at a time</li><li>extracts text from the PDF</li><li>detects the layout family</li><li>applies family-specific parsing logic</li><li>normalizes rows into one CSV schema</li><li>validates the result</li><li>safely updates the active dataset</li></ul><p>The Streamlit app then reads that CSV and adds:</p><ul><li>swimmer search</li><li>event, team, and date filtering</li><li>DQ/NT-safe time handling</li><li>trend charts</li><li>best-time summaries</li><li>event comparison</li></ul><p>This keeps responsibilities clean:</p><ul><li>parser = ingestion and normalization</li><li>CSV = stable intermediate dataset</li><li>Streamlit = analysis and visualization</li></ul><h3>Running the Parser</h3><p>Parsing is still a manual step, which makes the workflow explicit and easy to debug.</p><p>The command looks like this:</p><p>python3 src/swimming_app/pdf_parser.py \ --pdf-path &quot;PDF/&lt;file&gt;.pdf&quot; \ --active-csv-path &quot;${SWIM_DATA_PATH:-CSV/swim_data.csv}&quot; \ --backup-csv-path &quot;codex/swim_data_backup.csv&quot; \ --mode lenient</p><p>The important arguments are:</p><ul><li>— pdf-path: the input PDF to parse</li><li>— active-csv-path: the main CSV dataset to update on success</li><li>— backup-csv-path: the backup snapshot refreshed before parsing</li><li>— mode: validation mode</li></ul><p>The parser supports two modes:</p><ul><li>strict: the safer mode; it stops on suspicious output instead of updating the CSV</li><li>lenient: still blocks real structural failures, but treats lower-severity issues as warnings</li></ul><p>The script also supports optional — report-path and — candidate-path arguments for parse reports and inspection output, but the main workflow is simple: parse first, then update the CSV if validation succeeds.</p><h3>Why Validation Comes Before Writing</h3><p>Parsing alone is not enough. The script also has to decide whether the output is trustworthy.</p><p>Before writing to the active CSV, it checks things like:</p><ul><li>whether a meet name and date were found</li><li>whether event headers were detected</li><li>whether events actually produced rows</li><li>whether required fields are populated</li><li>whether relay rows are structurally valid</li><li>whether some family-specific values pass sanity checks</li></ul><p>This is one of the most important design decisions in the project.</p><p>A parser that fails loudly is easier to trust than one that silently writes bad data. If a PDF introduces a new shape or an unexpected token pattern, I want that to surface before it touches the main dataset.</p><h3>Safe Writes and New PDFs</h3><p>The script also writes conservatively. Before parsing, it refreshes a backup snapshot. If parsing or validation fails, the active CSV is not overwritten recklessly. Instead, the parser can produce:</p><ul><li>a parse report</li><li>a candidate CSV</li><li>a refreshed backup</li></ul><p>Only after validation succeeds does it replace the active CSV.</p><p>That becomes especially important when a new PDF arrives.</p><p>If the parser already understands the layout, the workflow is simple:</p><ol><li>run the parser</li><li>validate the result</li><li>update the CSV</li><li>open the app</li></ol><p>If the PDF uses a new or unsupported layout, the workflow changes:</p><ol><li>run the parser</li><li>inspect the detected family and parse report</li><li>review the candidate output</li><li>extend an existing family parser or add a new one</li><li>rerun the parser</li><li>validate again before updating the dataset</li></ol><p>That is the right failure mode. A new format should not silently enter the system.</p><h3>What the Streamlit App Adds</h3><p>Once the CSV has been updated, the Streamlit app becomes the analysis layer.</p><p>The local workflow becomes:</p><ol><li>parse the PDF</li><li>update the normalized CSV</li><li>run the app with make run</li><li>explore results in Streamlit</li></ol><p>At that point, the app can answer questions like:</p><ul><li>show all results for Foo</li><li>filter to Backstroke</li><li>narrow by team</li><li>narrow by date range</li><li>compare one swimmer across many meets</li><li>surface best performances over time</li></ul><p>The app is not doing anything magical beyond the normalized CSV layer, and that is exactly the point. Once the data is clean, the analysis becomes simple.</p><h3>Tools Used in Part 1</h3><p>Part 1 uses a focused toolset:</p><ul><li>Python 3.12 for the parser and app</li><li>pypdf for PDF text extraction</li><li>Python csv and json modules for exports and parse reports</li><li>pandas for loading and transforming normalized results</li><li>numpy for time cleaning and missing-value handling</li><li>Streamlit for the UI</li><li>Plotly for performance charts</li><li>Poetry for dependency management</li><li>Make for local commands</li><li>Ruff for formatting and linting</li></ul><h3>Code References</h3><p>Repo:</p><ul><li><a href="https://github.com/mishrasunny-coder/swimming-app">https://github.com/mishrasunny-coder/swimming-app</a></li></ul><p>Key files:</p><ul><li>Parser: <a href="https://github.com/mishrasunny-coder/swimming-app/blob/main/src/swimming_app/pdf_parser.py">https://github.com/mishrasunny-coder/swimming-app/blob/main/src/swimming_app/pdf_parser.py</a></li><li>Streamlit app: <a href="https://github.com/mishrasunny-coder/swimming-app/blob/main/src/swimming_app/streamlit_app.py">https://github.com/mishrasunny-coder/swimming-app/blob/main/src/swimming_app/streamlit_app.py</a></li><li>README: <a href="https://github.com/mishrasunny-coder/swimming-app/blob/main/README.md">https://github.com/mishrasunny-coder/swimming-app/blob/main/README.md</a></li><li>Makefile: <a href="https://github.com/mishrasunny-coder/swimming-app/blob/main/Makefile">https://github.com/mishrasunny-coder/swimming-app/blob/main/Makefile</a></li><li>Dependencies: <a href="https://github.com/mishrasunny-coder/swimming-app/blob/main/pyproject.toml">https://github.com/mishrasunny-coder/swimming-app/blob/main/pyproject.toml</a></li></ul><h3>Closing Thought</h3><p>Part 1 of this project was about building the foundation.</p><p>Before Docker, Cloud Run, and CI/CD, there had to be a reliable way to turn swim meet PDFs into usable data. That meant detecting layouts, extracting fields, normalizing rows, validating output, and building a lightweight Streamlit app on top of the result.</p><p>That work may not be the most glamorous part of the system, but it is the part that makes everything else possible.</p><p><strong>And that naturally leads into Part 2.</strong></p><p>Once the parser and Streamlit app were working locally, the next question was no longer, “Can I extract and analyze the data?” It became, “How do I package this so it runs the same way everywhere?”</p><p>That is where <strong>Docker</strong> enters the story and will be published in part 2 very soon. Stay Tuned :)</p><p>Hope you enjoyed the story and solution !!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=71246631643c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building an E-Commerce Database MCP Server with Python and Cursor]]></title>
            <link>https://medium.com/@mishra.sunny/building-an-e-commerce-database-mcp-server-with-python-and-cursor-2fe012df94e1?source=rss-4f2a0f316b56------2</link>
            <guid isPermaLink="false">https://medium.com/p/2fe012df94e1</guid>
            <category><![CDATA[llm-agent]]></category>
            <category><![CDATA[cursor-ai]]></category>
            <category><![CDATA[cursor-ide]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[mcp-server]]></category>
            <dc:creator><![CDATA[sunny mishra]]></dc:creator>
            <pubDate>Sun, 28 Sep 2025 04:30:08 GMT</pubDate>
            <atom:updated>2025-09-28T13:34:39.653Z</atom:updated>
            <content:encoded><![CDATA[<p>AI assistants are becoming more powerful not just because of LLMs, but because of the <strong>tools</strong> they can use. One such tool is the <strong>Model Context Protocol (MCP)</strong> — a standardized way to connect AI assistants (like <strong>Cursor</strong> or Claude) to external data and services.</p><p>In this tutorial, we’ll walk through an example MCP server that exposes a simple <strong>e-commerce database</strong>. By the end, we’ll know how it works, how to set it up, and how to query customers, orders, and products directly through your AI assistant.</p><h3>What is MCP</h3><p>The MCP or <strong>Model Context Protocol</strong> is a specification that allows AI assistants to talk to external tools through a common interface. Instead of writing custom integrations for each assistant, you write one MCP server and it can plug into any MCP-compatible client.</p><p>At its core, MCP has a few key <strong>primitives</strong>:</p><ul><li><strong>Servers</strong>: Processes that implement tools and respond to requests.</li><li><strong>Tools</strong>: Functions exposed by the server, each with defined parameters and return types.</li><li><strong>Clients</strong>: Applications (like Cursor IDE) that call these tools on behalf of the user.</li><li><strong>Messages</strong>: Requests and responses exchanged over stdio or sockets.</li></ul><p>Think of it as a way to give AI assistants <strong>structured APIs</strong> they can call, safely and consistently.</p><p>More information on MCP architecture can be found here <a href="https://modelcontextprotocol.io/docs/learn/architecture">https://modelcontextprotocol.io/docs/learn/architecture</a></p><h3>Project Architecture</h3><p>This example project contains three main components:</p><ul><li><strong>main.py</strong> → The MCP server implementation built with FastMCP.</li><li><strong>transactional_db.py</strong> → An in-memory database with sample customers, orders, and products.</li><li><strong>tests/test_server.py</strong> → Unit tests to confirm the server works as expected.</li></ul><pre>python-mcp/<br>├── main.py              # main file where MCP server is implemented<br>├── transactional_db.py  # Sample database<br>├── tests/<br>│   └── test_server.py   # Unit tests<br>├── requirements.txt     # Python dependencies<br>└── README.md</pre><h4>Database Schema</h4><p>The in-memory database is deliberately simple but covers the three essentials of any online shop</p><ul><li><strong>Customers</strong></li><li>Example: CUST123 → Alice Johnson (alice@example.com, 555-1234)</li><li><strong>Orders</strong></li><li>Example: ORD1001 → Alice’s order for $89.99 (Wireless Mouse + Keyboard) – Shipped</li><li><strong>Products</strong></li><li>Example: SKU100 → Wireless Mouse ($29.99, Stock: 42)</li></ul><p>This means our AI assistant can answer questions like <em>“What has Alice ordered?”</em> or <em>“How many keyboards are in stock?”</em></p><h4>MCP Tools</h4><p>In this tutorial we will implement the 5 MCP server tools below that will be used by LLM model claude4sonnet in cursor to answer any questions related to E-Commerce database</p><pre>| Tool                        | Purpose                   | Input                | Output                   |<br>| --------------------------- | ------------------------- | -------------------- | ------------------------ |<br>| `get_customer_info`         | Retrieve customer details | `customer_id: str`   | Customer record          |<br>| `get_order_details`         | Look up an order          | `order_id: str`      | Order details            |<br>| `check_inventory`           | Search products by name   | `product_name: str`  | Matching SKUs with stock |<br>| `get_customer_ids_by_name`  | Find IDs from full names  | `customer_name: str` | List of IDs              |<br>| `get_orders_by_customer_id` | List a customer’s orders  | `customer_id: str`   | Orders dictionary        |</pre><h4>Set Up Instructions</h4><p>Let’s jump to the fun part now</p><ol><li>Create a new project and initialize in git</li></ol><pre>mkdir python-mcp &amp;&amp; cd python-mcp</pre><p>2. Create and Activate Virtual Environment</p><pre>python3 -m venv venv<br>source venv/bin/activate   # This is on macOS. On Windows: venv\Scripts\activate</pre><p>3. Install MCP and other dependencies</p><pre>pip install mcp pydantic pytest pytest-asyncio</pre><p>4. Freeze Dependencies</p><pre>pip freeze &gt; requirements.txt</pre><p>5. Add Project Files</p><pre>python-mcp/<br>├── main.py              # MCP server implementation<br>├── transactional_db.py  # In-memory database<br>├── tests/<br>│   └── test_server.py   # Unit tests<br>├── requirements.txt     # Auto-generated in Step 4<br>└── README.md            # Documentation</pre><h4>Code written in each file</h4><p>Here is the code that you can copy paste in each file below according to the project structure</p><ol><li><strong>main.py</strong></li></ol><p>In this file we are essentially implementing tools that AI Assistants will use when responding back to the user with questions asked. Keep in mind that docstrings are extremely helpful and a requirement so add clear docstrings for each function/tool below</p><pre>import asyncio<br>from mcp.server.fastmcp import FastMCP<br>from transactional_db import CUSTOMERS_TABLE, ORDERS_TABLE, PRODUCTS_TABLE<br><br>mcp = FastMCP(&quot;ecommerce_tools&quot;)<br><br>@mcp.tool()<br>async def get_customer_info(customer_id: str) -&gt; str:<br>    &quot;&quot;&quot;Search for a customer using their unique identifier&quot;&quot;&quot;<br><br>    customer_info = CUSTOMERS_TABLE.get(customer_id)<br><br>    if not customer_info:<br>        return &quot;Customer not found&quot;<br><br>    return str(customer_info)<br><br>@mcp.tool()<br>async def get_order_details(order_id: str) -&gt; str:<br>    &quot;&quot;&quot;Get details about a specific order.&quot;&quot;&quot;<br>    await asyncio.sleep(1)<br>    order = ORDERS_TABLE.get(order_id)<br>    if not order:<br>        return f&quot;No order found with ID {order_id}.&quot;<br><br>    items = [<br>        PRODUCTS_TABLE[sku][&quot;name&quot;]<br>        for sku in order[&quot;items&quot;]<br>        if sku in PRODUCTS_TABLE<br>    ]<br>    return (<br>        f&quot;Order ID: {order_id}\n&quot;<br>        f&quot;Customer ID: {order[&#39;customer_id&#39;]}\n&quot;<br>        f&quot;Date: {order[&#39;date&#39;]}\n&quot;<br>        f&quot;Status: {order[&#39;status&#39;]}\n&quot;<br>        f&quot;Total: ${order[&#39;total&#39;]:.2f}\n&quot;<br>        f&quot;Items: {&#39;, &#39;.join(items)}&quot;<br>    )<br><br>@mcp.tool()<br>async def check_inventory(product_name: str) -&gt; str:<br>    &quot;&quot;&quot;Search inventory for a product by product name.&quot;&quot;&quot;<br>    await asyncio.sleep(1)<br>    matches = []<br>    for sku, product in PRODUCTS_TABLE.items():<br>        if product_name.lower() in product[&quot;name&quot;].lower():<br>            matches.append(<br>                f&quot;{product[&#39;name&#39;]} (SKU: {sku}) — Stock: {product[&#39;stock&#39;]}&quot;<br>            )<br>    return &quot;\n&quot;.join(matches) if matches else &quot;No matching products found.&quot;<br><br>@mcp.tool()<br>async def get_customer_ids_by_name(customer_name: str) -&gt; list[str]:<br>    &quot;&quot;&quot;Get customer IDs by using a customer&#39;s full name&quot;&quot;&quot;<br>    await asyncio.sleep(1)<br>    return [<br>        cust_id<br>        for cust_id, info in CUSTOMERS_TABLE.items()<br>        if info.get(&quot;name&quot;) == customer_name<br>    ]<br><br>@mcp.tool()<br>async def get_orders_by_customer_id(<br>    customer_id: str,<br>) -&gt; dict[str, dict[str, str]]:<br>    &quot;&quot;&quot;Get orders by customer ID&quot;&quot;&quot;<br>    await asyncio.sleep(1)<br>    return {<br>        order_id: order<br>        for order_id, order in ORDERS_TABLE.items()<br>        if order.get(&quot;customer_id&quot;) == customer_id<br>    }<br><br>if __name__ == &quot;__main__&quot;:<br>    mcp.run(transport=&quot;stdio&quot;)</pre><p>2. <strong>transactional_db.py</strong></p><p>This is in-memory database that LLMs will use as a resource to take a look at this i.e. fetch information from here before summarizing their response to the user.</p><pre>CUSTOMERS_TABLE = {<br>    &quot;CUST123&quot;: {<br>        &quot;name&quot;: &quot;Alice Johnson&quot;,<br>        &quot;email&quot;: &quot;alice@example.com&quot;,<br>        &quot;phone&quot;: &quot;555-1234&quot;,<br>    },<br>    &quot;CUST456&quot;: {<br>        &quot;name&quot;: &quot;Bob Smith&quot;,<br>        &quot;email&quot;: &quot;bob@example.com&quot;,<br>        &quot;phone&quot;: &quot;555-5678&quot;,<br>    },<br>}<br><br>ORDERS_TABLE = {<br>    &quot;ORD1001&quot;: {<br>        &quot;customer_id&quot;: &quot;CUST123&quot;,<br>        &quot;date&quot;: &quot;2024-04-01&quot;,<br>        &quot;status&quot;: &quot;Shipped&quot;,<br>        &quot;total&quot;: 89.99,<br>        &quot;items&quot;: [&quot;SKU100&quot;, &quot;SKU200&quot;],<br>    },<br>    &quot;ORD1015&quot;: {<br>        &quot;customer_id&quot;: &quot;CUST123&quot;,<br>        &quot;date&quot;: &quot;2024-05-17&quot;,<br>        &quot;status&quot;: &quot;Processing&quot;,<br>        &quot;total&quot;: 45.50,<br>        &quot;items&quot;: [&quot;SKU300&quot;],<br>    },<br>    &quot;ORD1022&quot;: {<br>        &quot;customer_id&quot;: &quot;CUST456&quot;,<br>        &quot;date&quot;: &quot;2024-06-04&quot;,<br>        &quot;status&quot;: &quot;Delivered&quot;,<br>        &quot;total&quot;: 120.00,<br>        &quot;items&quot;: [&quot;SKU100&quot;, &quot;SKU100&quot;],<br>    },<br>}<br><br>PRODUCTS_TABLE = {<br>    &quot;SKU100&quot;: {&quot;name&quot;: &quot;Wireless Mouse&quot;, &quot;price&quot;: 29.99, &quot;stock&quot;: 42},<br>    &quot;SKU200&quot;: {&quot;name&quot;: &quot;Keyboard&quot;, &quot;price&quot;: 59.99, &quot;stock&quot;: 18},<br>    &quot;SKU300&quot;: {&quot;name&quot;: &quot;USB-C Cable&quot;, &quot;price&quot;: 15.50, &quot;stock&quot;: 77},<br>}</pre><p>3. <strong>tests/test_server.py</strong></p><pre>import asyncio<br>import pytest<br>from contextlib import AsyncExitStack<br>from mcp import ClientSession, StdioServerParameters<br>from mcp.client.stdio import stdio_client<br><br>SERVER_PATH = &quot;/Users/mishrasunny/Documents/python-mcp/main.py&quot;<br>EXPECTED_TOOLS = [<br>    &quot;get_customer_info&quot;,<br>    &quot;get_order_details&quot;,<br>    &quot;check_inventory&quot;,<br>    &quot;get_customer_ids_by_name&quot;,<br>    &quot;get_orders_by_customer_id&quot;,<br>]<br><br>@pytest.mark.asyncio<br>async def test_mcp_server_connection():<br>    &quot;&quot;&quot;Connect to an MCP server and verify the tools&quot;&quot;&quot;<br><br>    exit_stack = AsyncExitStack()<br><br>    server_params = StdioServerParameters(<br>        command=&quot;python&quot;, args=[SERVER_PATH], env=None<br>    )<br><br>    stdio_transport = await exit_stack.enter_async_context(<br>        stdio_client(server_params)<br>    )<br>    stdio, write = stdio_transport<br>    session = await exit_stack.enter_async_context(<br>        ClientSession(stdio, write)<br>    )<br><br>    await session.initialize()<br><br>    response = await session.list_tools()<br>    tools = response.tools<br>    tool_names = [tool.name for tool in tools]<br>    tool_descriptions = [tool.description for tool in tools]<br><br>    print(&quot;\nYour server has the following tools:&quot;)<br>    for tool_name, tool_description in zip(tool_names, tool_descriptions):<br>        print(f&quot;{tool_name}: {tool_description}&quot;)<br><br>    assert sorted(EXPECTED_TOOLS) == sorted(tool_names)<br><br>    await exit_stack.aclose()</pre><p>4. <strong>requirements.txt</strong></p><p>This file should be auto generated when you run pip freeze &gt;requirements.txt</p><p>5. <strong>Run Tests</strong></p><p>Run this simple command from the root of your directory python-mcp</p><pre>pytest tests/test_server.py -v</pre><h4>Download Cursor for macOS</h4><p>We will demo how AI agents will use mcp tools and resources to answer user’s questions asked about the data using cursor. Downloading and setting up cursor is easy and part of this demo</p><p>To download and set up cursor please visit <a href="https://cursor.com/agents">https://cursor.com/agents</a> and download for macOS. First time users have to set up an account and can use cursor for free but it’s substantially limited.</p><p>Once downloaded successfully and cursor IDE is set up follow the instructions below</p><ol><li>Go to cursor settings -&gt; MCP and Integrations -&gt; Custom MCP Server</li><li>Add the following in the mcp.json file</li></ol><pre>{<br>  &quot;mcpServers&quot;: {<br>   &quot;ecommerce-db-server&quot;: {<br>     &quot;command&quot;: &quot;/path/to/your/directory/python-mcp/venv/bin/python&quot;,<br>     &quot;args&quot;: [<br>       &quot;/path/to/your/directory/python-mcp/main.py&quot;<br>     ],<br>     &quot;description&quot;: &quot;A set of tools that you can use to look up customer, order, and product information in a transactional database&quot;<br>   }<br> }<br>}</pre><p>Once completed then cursor is all set up with your own implemented mcp-server.</p><h3>Demo</h3><p>Now let’s demo a few prompts to see how accurate LLM provides information when prompted in cursor chat</p><p>Please see this screenshot below. LLM accurately calls get_customer_info() tool or function that we implemented in mcp server main.py file when user asks “Get me information on customer with the name Alice Johnson”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/746/1*-FZpoo9z0bBegBOk6k7omQ.png" /></figure><p>In the screenshot above LLM calls get_customer_info which passes this parameter below</p><pre>{<br>  &quot;customer_id&quot;: &quot;CUST123&quot;<br>}</pre><p>And the result is</p><pre>{&quot;result&quot;:&quot;{&#39;name&#39;: &#39;Alice Johnson&#39;, <br>&#39;email&#39;: &#39;alice@example.com&#39;, &#39;phone&#39;: &#39;555-1234&#39;}&quot;}<br></pre><p>LLM then decides to use <strong>get_customer_info</strong> tool based on the prompt provided by the user by sending JSON object i.e. parameter to the MCP client above.</p><p>MCP client then takes this JSON and calls MCP server like this</p><pre># This is what got executed in your main.py<br>await get_customer_ids_by_name(customer_name=&quot;Alice Johnson&quot;)</pre><p>MCP server then processes this function</p><pre>@mcp.tool()<br>async def get_customer_ids_by_name(customer_name: str) -&gt; list[str]:<br>    &quot;&quot;&quot;Get customer IDs by using a customer&#39;s full name&quot;&quot;&quot;<br>    await asyncio.sleep(1)  # Simulated processing time<br>    return [<br>        cust_id<br>        for cust_id, info in CUSTOMERS_TABLE.items()<br>        if info.get(&quot;name&quot;) == customer_name  # Matched &quot;Alice Johnson&quot;<br>    ]</pre><p>Server returns [“CUST123”]</p><p>MCP Client forwarded the result back to the LLM</p><p>LLM summarizes the result in Natural Language and returns this response to the user</p><pre>Here&#39;s the information for customers with the name Alice Johnson:<br>👤 Customer Information<br>Customer ID: CUST123<br>Name: Alice Johnson<br>Email: alice@example.com<br>Phone: 555-1234<br>Based on the database, there is one customer named Alice Johnson with the customer ID CUST123. This customer has complete contact information including email and phone number on file.</pre><p>And that’s it. If the set up works fine for the users then feel free to prompt LLM with more questions. Keep in mind this is a toy example but we can always use this as a base and extend our MCP server capabilities and add more tools</p><h3>Conclusion</h3><p>Hope you enjoyed the tutorial :)</p><p>This project demonstrates how MCP servers can bridge AI assistants with structured data sources. By following this tutorial, you now have a foundation to build more complex, production-ready integrations for real-world applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2fe012df94e1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Basic gRPC Service using Python (Part 2) — Add Tests]]></title>
            <link>https://medium.com/@mishra.sunny/building-a-basic-grpc-service-using-python-part-2-add-tests-7b5d7ebac6b5?source=rss-4f2a0f316b56------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b5d7ebac6b5</guid>
            <category><![CDATA[integration-testing]]></category>
            <category><![CDATA[grpc-client]]></category>
            <category><![CDATA[e2e-testing]]></category>
            <category><![CDATA[qa]]></category>
            <category><![CDATA[unit-testing]]></category>
            <dc:creator><![CDATA[sunny mishra]]></dc:creator>
            <pubDate>Tue, 31 Dec 2024 05:15:18 GMT</pubDate>
            <atom:updated>2024-12-31T05:15:18.790Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building a Basic gRPC Service using Python (Part 2) — Add Tests</h3><h3>Introduction 🌟</h3><p>In this tutorial, we will add comprehensive testing to the gRPC service created in <a href="https://medium.com/@mishra.sunny/building-a-basic-grpc-service-using-python-part-1-04dc418c25dc">Part 1</a>. Testing is crucial to ensure the service is reliable, scalable, and meets its requirements. By the end of this guide, you will have a robust testing framework consisting of:</p><ol><li><strong>Unit Tests</strong>: Validate individual service logic methods.</li><li><strong>Integration Tests</strong>: Test the interaction of the service with the gRPC framework and dependencies.</li><li><strong>End-to-End (E2E) Tests</strong>: Validate the behavior from the client to the server.</li></ol><h3>Updated Project Structure 📂</h3><p>We will organize our project as follows:</p><pre>GRPC_TESTING/<br>│<br>├── .pytest_cache/                    # Pytest cache directory (auto-generated)<br>│<br>├── tests/                            # Directory for unit, integration, and E2E tests<br>│   ├── e2e/<br>│   │   ├── __init__.py               # Marks e2e directory as a Python package<br>│   │   └── test_calculator_e2e.py    # E2E tests using pytest<br>│   ├── integration/<br>│   │   ├── __init__.py               # Marks integration directory as a Python package<br>│   │   └── test_calculator_integration.py # Integration tests using pytest<br>│   └── unit/<br>│       ├── __init__.py               # Marks unit directory as a Python package<br>│       └── test_calculator_unit.py   # Unit tests for the calculator service<br>│<br>├── venv/                             # Virtual environment directory (Python dependencies)<br>│<br>├── .gitignore                        # Git ignore file<br>├── calculator_pb2_grpc.py            # Auto-generated gRPC Python code<br>├── calculator_pb2.py                 # Auto-generated protobuf Python code<br>├── calculator.proto                  # Protobuf definition file<br>├── client.py                         # gRPC client implementation<br>├── docker-compose.yml                # Docker Compose configuration file<br>├── Dockerfile                        # Dockerfile for containerizing the service<br>├── Makefile                          # Makefile for managing tasks (tests, builds, etc.)<br>├── poetry.lock                       # Poetry lock file for dependency management<br>├── pyproject.toml                    # Poetry configuration file<br>├── README.md                         # Project README file<br>└── server.py                         # Main gRPC server implementation</pre><h3>Step 1: Unit Tests 🧪</h3><p>Unit tests validate individual methods of the service logic. We will test the Add and Subtract methods of the CalculatorServicer class.</p><h3>Implementation 📝</h3><p>Create the file tests/unit/test_calculator_unit.py and add the following code:</p><pre>from server import CalculatorServicer<br>import calculator_pb2<br><br><br>def test_add():<br>    &quot;&quot;&quot;Test the Add method of the Calculator service.&quot;&quot;&quot;<br>    servicer = CalculatorServicer()<br>    request = calculator_pb2.operands(a=5, b=3)<br>    response = servicer.Add(request, None)<br>    assert response.value == 8, f&quot;Expected 8, but got {response.value}&quot;<br><br><br>def test_subtract():<br>    &quot;&quot;&quot;Test the Subtract method of the Calculator service.&quot;&quot;&quot;<br>    servicer = CalculatorServicer()<br>    request = calculator_pb2.operands(a=10, b=4)<br>    response = servicer.Subtract(request, None)<br>    assert response.value == 6, f&quot;Expected 6, but got {response.value}&quot;</pre><h3>Makefile Update ⚙️</h3><p>Add a target to run unit tests:</p><pre># Run unit tests<br>test-unit:<br> @echo &quot;Running unit tests...&quot;<br> poetry run pytest tests/unit --disable-warnings -v</pre><p>Run the command</p><p>make test-unit</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6TCRmV7oFugXgEYY4htSsA.png" /></figure><p>Ensure the tests pass before proceeding. ✅</p><h3>Step 2: Integration Tests 🔗</h3><p>Integration tests validate the service’s functionality with the gRPC framework and its dependencies.</p><h3>Implementation</h3><p>Create the file tests/integration/test_calculator_integration.py and add the following code:</p><pre>import grpc<br>from concurrent import futures<br>import calculator_pb2<br>import calculator_pb2_grpc<br>from server import CalculatorServicer<br><br><br>def start_grpc_server():<br>    &quot;&quot;&quot;Starts a local gRPC server for testing.&quot;&quot;&quot;<br>    server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))<br>    calculator_pb2_grpc.add_CalculatorServicer_to_server(CalculatorServicer(), server)<br>    <br>    # Bind to port 0 to get an available port dynamically<br>    port = server.add_insecure_port(&#39;[::]:0&#39;)<br>    server.start()<br>    return server, port<br><br><br><br>def test_add_method():<br>    &quot;&quot;&quot;Tests the Add method of the Calculator service.&quot;&quot;&quot;<br>    server, port = start_grpc_server()  # Unpack the tuple<br>    try:<br>        channel = grpc.insecure_channel(f&quot;localhost:{port}&quot;)  # Use the dynamically bound port<br>        stub = calculator_pb2_grpc.CalculatorStub(channel)<br>        response = stub.Add(calculator_pb2.operands(a=5, b=3))<br>        assert response.value == 8, f&quot;Expected 8, got {response.value}&quot;<br>    finally:<br>        server.stop(None)  # Call stop on the server object<br><br><br>def test_subtract_method():<br>    &quot;&quot;&quot;Tests the Subtract method of the Calculator service.&quot;&quot;&quot;<br>    server, port = start_grpc_server()  # Unpack the tuple<br>    try:<br>        channel = grpc.insecure_channel(f&quot;localhost:{port}&quot;)  # Use the dynamically bound port<br>        stub = calculator_pb2_grpc.CalculatorStub(channel)<br>        response = stub.Subtract(calculator_pb2.operands(a=10, b=4))<br>        assert response.value == 6, f&quot;Expected 6, got {response.value}&quot;<br>    finally:<br>        server.stop(None)  # Call stop on the server object</pre><h3>Makefile Update ⚙️</h3><p>Add a target to run integration tests in the existing Makefile</p><pre># Run integration tests<br>test-integration:<br> @echo &quot;Running integration tests...&quot;<br> poetry run pytest tests/integration --disable-warnings -v</pre><p>Once completed make sure to run make run first to start the services and then run make test-integration and the tests should pass ✅</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mVg3IJm1bMWvzE1YGF3QXg.png" /></figure><h3>Step 3: End-to-End (E2E) Tests 🚀</h3><p>E2E tests validate the service’s behavior from the client to the server.</p><h3>Implementation</h3><p>Create the file tests/e2e/test_calculator_e2e.py and add the following code</p><p>Then add the following tests</p><pre>import grpc<br>import calculator_pb2<br>import calculator_pb2_grpc<br>import pytest<br><br><br>@pytest.fixture(scope=&quot;module&quot;)<br>def grpc_stub():<br>    &quot;&quot;&quot;Creates a gRPC stub for connecting to the running Calculator service.&quot;&quot;&quot;<br>    channel = grpc.insecure_channel(&quot;localhost:50051&quot;)<br>    stub = calculator_pb2_grpc.CalculatorStub(channel)<br>    return stub<br><br><br>def test_add_e2e(grpc_stub):<br>    &quot;&quot;&quot;End-to-end test for the Add method.&quot;&quot;&quot;<br>    response = grpc_stub.Add(calculator_pb2.operands(a=5, b=3))<br>    assert response.value == 8, f&quot;Expected 8, got {response.value}&quot;<br><br><br>def test_subtract_e2e(grpc_stub):<br>    &quot;&quot;&quot;End-to-end test for the Subtract method.&quot;&quot;&quot;<br>    response = grpc_stub.Subtract(calculator_pb2.operands(a=10, b=4))<br>    assert response.value == 6, f&quot;Expected 6, got {response.value}&quot;</pre><p>I will spend some time to explain the code above for e2e tests.</p><h4>Imports</h4><pre>import grpc<br>import calculator_pb2<br>import calculator_pb2_grpc<br>import pytest</pre><ul><li><strong>grpc</strong>: The core Python gRPC library for communication between the client and server.</li><li><strong>calculator_pb2 and </strong><strong>calculator_pb2_grpc</strong>: Generated Python files from the calculator.proto definition. These provide the request and response message classes as well as the client stub.</li></ul><h4>gRPC Stub Fixture</h4><pre>@pytest.fixture(scope=&quot;module&quot;)<br>def grpc_stub():<br>    &quot;&quot;&quot;Creates a gRPC stub for connecting to the running Calculator service.&quot;&quot;&quot;<br>    channel = grpc.insecure_channel(&quot;localhost:50051&quot;)<br>    stub = calculator_pb2_grpc.CalculatorStub(channel)<br>    return stub</pre><ul><li><strong>Purpose</strong>: This is a reusable test fixture that creates a gRPC stub for the Calculator service.</li><li>The <strong>stub</strong> acts as the client, allowing you to call the service’s methods (Add, Subtract, etc.).</li><li><strong>channel</strong>: Establishes a communication channel with the gRPC server running on localhost:50051.</li><li><strong>Scope</strong>: module ensures the fixture is created once per test module, and the same stub is reused across all tests.</li></ul><p><strong>How It Works</strong>:</p><ul><li>When a test function requires the grpc_stub fixture, the pytest framework automatically provides it.</li></ul><h4>Test: Add Method</h4><pre>def test_add_e2e(grpc_stub):<br>    &quot;&quot;&quot;End-to-end test for the Add method.&quot;&quot;&quot;<br>    response = grpc_stub.Add(calculator_pb2.operands(a=5, b=3))<br>    assert response.value == 8, f&quot;Expected 8, got {response.value}&quot;</pre><ul><li><strong>Test Description</strong>: This test calls the Add method on the Calculator service to validate its behavior.</li><li><strong>Steps</strong>:</li><li>The Add method is called via the stub (grpc_stub.Add), passing in an operands message containing a=5 and b=3.</li><li>The service processes the request and returns a Result message containing the sum (value=8).</li><li>The test checks if the value returned by the response matches the expected result (8).</li></ul><h4>Test: Subtract Method</h4><pre>def test_subtract_e2e(grpc_stub):<br>    &quot;&quot;&quot;End-to-end test for the Subtract method.&quot;&quot;&quot;<br>    response = grpc_stub.Subtract(calculator_pb2.operands(a=10, b=4))<br>    assert response.value == 6, f&quot;Expected 6, got {response.value}&quot;</pre><p>Now Update the Makefile similar to what we did above for unit and integration tests</p><pre># Run end-to-end (E2E) tests<br>test-e2e:<br> @echo &quot;Running end-to-end (E2E) tests...&quot;<br> poetry run pytest tests/e2e --disable-warnings -v</pre><p>Now once updated run make test-e2e . Keep in mind service has to be up and running so make sure make run is run or we can also check docker ps -a to make sure gRPC service is up and running</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XWQp-EORwXdT7ixE7adEWw.png" /></figure><h3>Conclusion 🎉</h3><p>You have successfully implemented unit, integration, and E2E tests for your gRPC service. These tests ensure the service functions correctly at all levels. In the next part, we will automate the testing process using GitHub workflows and explore BDD testing with behave.</p><h3>Feedback</h3><p>Please try these steps and share your feedback to help improve this tutorial. 💬</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b5d7ebac6b5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Basic gRPC Service using Python (Part 1)]]></title>
            <link>https://medium.com/@mishra.sunny/building-a-basic-grpc-service-using-python-part-1-04dc418c25dc?source=rss-4f2a0f316b56------2</link>
            <guid isPermaLink="false">https://medium.com/p/04dc418c25dc</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[grpc-python]]></category>
            <category><![CDATA[grpc-api]]></category>
            <category><![CDATA[grpc]]></category>
            <dc:creator><![CDATA[sunny mishra]]></dc:creator>
            <pubDate>Sun, 15 Dec 2024 19:26:42 GMT</pubDate>
            <atom:updated>2024-12-15T20:33:03.284Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RTzj2fgwPW9ajulzCOi89A.png" /></figure><h4>Introduction</h4><p>Hi All!</p><p>gRPC is a high-performance, open-source, and universal Remote Procedure Call (RPC) framework designed to help developers build scalable microservices. While gRPC simplifies communication across services, ensuring these services are reliable through comprehensive testing is crucial.</p><p>In this tutorial, I will guide you through building a basic gRPC service for performing addition and subtraction operations. We’ll then test the service by running grpcurl command for now to test the service but in the next part I will dockerize the service and create unit, integration, and e2e tests. While this tutorial is implemented on <strong>macOS</strong>, the steps can easily be adapted for <strong>Windows</strong> or <strong>Linux</strong>.</p><h4>Building the Basic gRPC Service</h4><p>We will build a simple gRPC service with two operations: Add and Subtract. The service takes two numbers as input and returns their sum or difference. Using <strong>Protocol Buffers (protobuf)</strong>, we will define the structure and behavior of the service and implement it in Python.</p><h4>Steps to Implement the gRPC Service</h4><ol><li>Define the gRPC Service.</li><li>Generate Python code from the Proto file.</li><li>Implement the gRPC Server.</li><li>Implement the gRPC Client.</li></ol><h4>Project Setup</h4><p>Before building the service, let’s set up our project and create a virtual environment using <a href="https://code.visualstudio.com/docs/python/python-tutorial">vscode</a></p><h4>Step 1: Create the Project Folder</h4><ol><li>Create a folder named grpc_service in your <strong>Documents</strong> directory or any preferred location on your MacBook.</li><li>Ensure <strong>Python 3</strong> is installed. If not, download it from <a href="https://www.python.org/downloads/macos/">Python Downloads for macOS</a>.</li></ol><h4>Step 2: Install Dependencies Using Poetry</h4><p>We will use <a href="https://pypi.org/project/poetry/">Poetry</a> to manage dependencies.</p><p>Now let’s follow the steps below.</p><ul><li><strong><em>Create a Python virtual environment in the </em></strong><strong><em>grpc_service folder</em></strong></li></ul><pre># Create Virtual Environment<br>python3 -m venv venv<br><br># Activate the Virtual Environment<br>source venv/bin/activate<br></pre><ul><li><strong><em>Install Poetry</em></strong></li></ul><pre>pip install poetry</pre><ul><li><strong><em>Initialize Poetry for the project</em></strong></li></ul><pre>poetry init</pre><p>Follow the prompts:</p><ol><li><strong>Package name:</strong> grpc-server</li><li><strong>Version:</strong> Press Enter (default is 0.1.0)</li><li><strong>Description:</strong> Basic gRPC Service</li><li><strong>Author:</strong> Skip (type n)</li><li><strong>License:</strong> Press Enter</li><li><strong>Compatible Python versions:</strong> Press Enter</li></ol><ul><li><strong><em>Add gRPC dependencies</em></strong></li></ul><pre>poetry add grpcio-tools --allow-prereleases</pre><p><strong>Note:</strong> <em>In some cases, you might need to install the </em><em>grpcio-reflection package for enhanced functionality. This depends on your operating system.</em></p><p>Now let’s start building the service after successful project setup</p><h4>Step 1: Define the gRPC Service</h4><p>Create a file named calculator.proto in the project folder with the following content</p><pre>syntax = &quot;proto3&quot;;<br><br>service Calculator {<br>    rpc Add (operands) returns (Result);<br>    rpc Subtract (operands) returns (Result);<br>}<br><br>message operands {<br>    double a = 1;<br>    double b = 2;<br>}<br><br>message Result {<br>    double value = 1;<br>}</pre><h4>Step 2: Generate Python Code from Proto File</h4><p>Run the following command in the terminal to generate Python code from the .proto file</p><pre>python -m grpc_tools.protoc -I. --python_out=. --grpc_python_out=. calculator.proto</pre><p>This command will generate two files</p><ul><li>calculator_pb2.py</li><li>calculator_pb2_grpc.py</li></ul><p>We will use these files to implement the server and client.</p><h4>Step 3: Implement the gRPC Server</h4><p>Create a file named server.py and add the following code</p><pre>import grpc<br>from concurrent import futures<br>import calculator_pb2<br>import calculator_pb2_grpc<br>from grpc_reflection.v1alpha import reflection<br><br><br>class CalculatorServicer(calculator_pb2_grpc.CalculatorServicer):<br>    def Add (self, request, context):<br>        result = request.a + request.b<br>        return calculator_pb2.Result(value=result)<br>    <br>    def Subtract(self, request, context):<br>        result = request.a - request.b<br>        return calculator_pb2.Result(value=result)<br><br>def serve():<br>    server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))<br>    calculator_pb2_grpc.add_CalculatorServicer_to_server(CalculatorServicer(), server)<br>    # Enable reflection for the Calculator service<br>    SERVICE_NAMES = (<br>        calculator_pb2.DESCRIPTOR.services_by_name[&#39;Calculator&#39;].full_name,<br>        reflection.SERVICE_NAME,<br>    )<br>    reflection.enable_server_reflection(SERVICE_NAMES, server)<br>    server.add_insecure_port(&#39;[::]:50051&#39;)<br>    server.start()<br>    server.wait_for_termination()<br><br>if __name__ == &#39;__main__&#39;:<br>    serve()</pre><h4>Step 4: Implement the gRPC Client</h4><p>Create a file named client.py and add the following code</p><pre>import grpc<br>import calculator_pb2<br>import calculator_pb2_grpc<br><br>def run():<br>    with grpc.insecure_channel(&#39;localhost:50051&#39;) as channel:<br>        stub = calculator_pb2_grpc.CalculatorStub(channel)<br>        response = stub.Add(calculator_pb2.operands(a=5, b=3))<br>        print(f&quot;Add: 5 + 3 = {response.value}&quot;)<br>        response = stub.Subtract(calculator_pb2.operands(a=5, b=3))<br>        print(f&quot;Subtract: 5 - 3 = {response.value}&quot;)<br><br>if __name__ == &#39;__main__&#39;:<br>    run()</pre><p>And that’s it our gRPC service should be good to go. Next section describes how to test your service.</p><h4>Testing the Service Locally</h4><p>Now the client and server are implemented but need to make sure they infact work :)</p><p>But before testing make sure grpcurl is installed. If not already installed please follow <a href="https://formulae.brew.sh/formula/grpcurl">https://formulae.brew.sh/formula/grpcurl</a></p><p>Assuming grpcurl is successfully installed and now is the time to test your service :)</p><p>In vscode terminal run python server.py . This command will start the server if our setup is good.</p><p>Open a new terminal in vscode and this time run the following command</p><pre># For testing Addition Service<br>grpcurl -plaintext -d &#39;{&quot;a&quot;: 10, &quot;b&quot;: 5}&#39; localhost:50051 Calculator.Add<br><br># Output<br><br>{<br>  &quot;value&quot;: 15<br>}<br><br># For testing Subtraction Service<br>grpcurl -plaintext -d &#39;{&quot;a&quot;: 10, &quot;b&quot;: 5}&#39; localhost:50051 Calculator.Subtract<br><br># Output<br>{<br>  &quot;value&quot;: 5<br>}</pre><p>And our service works like a charm.</p><h3>Conclusion</h3><p>Congratulations! You’ve successfully implemented and tested a basic gRPC service. While this tutorial was implemented on macOS, the steps can easily be adapted for other operating systems like Windows or Linux.</p><p>In the next part of this series, I will show you how to <strong>dockerize</strong> the service and manage it using make commands. Stay tuned!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=04dc418c25dc" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>