<?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 Amiya Mandal on Medium]]></title>
        <description><![CDATA[Stories by Amiya Mandal on Medium]]></description>
        <link>https://medium.com/@plutoniumguy?source=rss-31cc3e8e2721------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Stories by Amiya Mandal on Medium</title>
            <link>https://medium.com/@plutoniumguy?source=rss-31cc3e8e2721------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 05:23:00 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@plutoniumguy/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[ How to Use MCP Server (It’s Just Fancy RPC, Bro — But for AI)]]></title>
            <link>https://plutoniumguy.medium.com/how-to-use-mcp-server-its-just-fancy-rpc-bro-but-for-ai-c6258d37de85?source=rss-31cc3e8e2721------2</link>
            <guid isPermaLink="false">https://medium.com/p/c6258d37de85</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[mcp-server]]></category>
            <dc:creator><![CDATA[Amiya Mandal]]></dc:creator>
            <pubDate>Sat, 12 Apr 2025 11:25:46 GMT</pubDate>
            <atom:updated>2025-04-12T11:30:18.552Z</atom:updated>
            <content:encoded><![CDATA[<h3>😎 How to Use MCP Server (It’s Just Fancy RPC, Bro — But for AI)</h3><p>So, you’ve heard the hype:<br> <strong>“MCP is the future of LLM integration!”</strong><br> <strong>“It’s how tools talk to Claude!”</strong><br> <strong>“It’s magic!”</strong></p><p>Let me break it to you gently:<br> <strong>MCP (Model Context Protocol)</strong> is just well-structured JSON-RPC… dressed up and ready to impress your AI agents.</p><p>But hey — it works, it’s clean, and it’s actually super fun to build with.<br> So, let’s dive in and create our own <strong>MCP server in Go</strong>, plug in a local LLM with <strong>Ollama</strong>, and expose some tools for real-world use.</p><h3>🧠 What Even Is Model Context Protocol?</h3><p><strong>MCP</strong> stands for <strong>Model Context Protocol</strong>. It’s a way to expose <em>structured, schema-defined tools</em> to large language models (LLMs).</p><p>In simple terms:</p><blockquote><em>You describe tools → MCP formats them → LLMs understand and call them.</em></blockquote><p>Under the hood, it’s built on:</p><ul><li><strong>JSON-RPC</strong> for transport</li><li><strong>Schemas</strong> for tool definitions</li><li><strong>validation + metadata</strong></li></ul><p>It’s what Anthropic’s Claude uses to expose tools like calculators, file fetchers, search agents, etc. But it’s not tied to Claude — you can use it with <strong>Ollama</strong>, <strong>Open Source LLMs</strong>, or your own agents.</p><h3>🧵 But Wait… Isn’t This Just RPC?</h3><p>Yup.<br> This is JSON-RPC — the same protocol that:</p><ul><li>Powers <strong>Ethereum and Bitcoin nodes</strong></li><li>Is used in <strong>crypto exchanges</strong></li><li>Has been exploited by <strong>viruses and trojans</strong> for years (because it’s that efficient 😅)</li></ul><p>So yeah, it’s not <em>new</em> tech.<br> But MCP wraps it in clean tooling, adds superpowers like schema enforcement, and makes it <strong>LLM-friendly</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E_7rL4tyAkKOuH9QCJjHgQ.png" /></figure><h3>🛠 Getting Started with MCP in Go</h3><p>You’ll need:</p><ul><li>Go (for code)</li><li>Ollama (for local LLM)</li><li>mcp-go (for building MCP servers)</li></ul><h4>📦 Step 1: Install Go</h4><p>Follow the guide 👉 <a href="https://go.dev/doc/install">https://go.dev/doc/install</a></p><h4>🧠 Step 2: Install Ollama</h4><p>Ollama = run LLMs like qwen:2.5, qwq, etc. <em>locally</em>.<br> No API keys. No rate limits. Just pure edge-AI bliss.</p><pre>$ ollama run qwen:2.5</pre><h4>⚙️ Step 3: Setup the Project</h4><pre>$ mkdir mcp-demo<br>$ cd mcp-demo<br>$ go mod init mcp-demo</pre><p>Install dependencies:</p><pre>$ go get github.com/mark3labs/mcp-go<br>$ go get github.com/sirupsen/logrus</pre><h3>✍️ Step 4: The Code</h3><p>You’re gonna build:</p><ul><li>A <strong>calculator</strong> tool (basic math, baby)</li><li>An <strong>image downloader</strong> (because why not)</li></ul><p>💻 Here’s your full main.go code:</p><pre>package main<br><br>import (<br> &quot;context&quot;<br> &quot;errors&quot;<br> &quot;fmt&quot;<br> &quot;io&quot;<br> &quot;net/http&quot;<br> &quot;net/url&quot;<br> &quot;os&quot;<br> &quot;os/signal&quot;<br> &quot;path/filepath&quot;<br> &quot;strings&quot;<br> &quot;syscall&quot;<br> &quot;time&quot;<br><br> &quot;github.com/mark3labs/mcp-go/mcp&quot;<br> &quot;github.com/mark3labs/mcp-go/server&quot;<br> &quot;github.com/sirupsen/logrus&quot;<br>)<br><br>var logger = logrus.New()<br><br>func init() {<br> logger.SetFormatter(&amp;logrus.TextFormatter{FullTimestamp: true})<br> logger.SetLevel(logrus.InfoLevel)<br>}<br><br>func main() {<br> // ────────────────────────────────────<br> // 1. Create MCP server with logging &amp; recovery<br> // ────────────────────────────────────<br> s := server.NewMCPServer(<br>  &quot;MCP Demo&quot;, // name<br>  &quot;1.2.0&quot;,    // version<br>  server.WithResourceCapabilities(true, true),<br>  server.WithLogging(), // built‑in request logging middleware<br>  server.WithRecovery(),<br> )<br><br> // ────────────────────────────────────<br> // 2. Register tools<br> // ────────────────────────────────────<br> registerCalculatorTool(s)<br> registerDownloadImageTool(s)<br><br> // ────────────────────────────────────<br> // 3. Run server with graceful shutdown<br> // ────────────────────────────────────<br> go func() {<br>  if err := server.ServeStdio(s); err != nil {<br>   logger.Fatalf(&quot;server error: %v&quot;, err)<br>  }<br> }()<br> sigCh := make(chan os.Signal, 1)<br> signal.Notify(sigCh, syscall.SIGINT, syscall.SIGTERM)<br> &lt;-sigCh<br> logger.Info(&quot;shutting down… (hit Ctrl+C again to force)&quot;)<br>}<br><br>// ───────────────────────────────────────<br>// calculator tool + handler<br>// ───────────────────────────────────────<br>func registerCalculatorTool(s *server.MCPServer) {<br> calculatorTool := mcp.NewTool(&quot;calculate&quot;,<br>  mcp.WithDescription(&quot;Perform basic arithmetic operations&quot;),<br>  mcp.WithString(&quot;operation&quot;,<br>   mcp.Required(),<br>   mcp.Description(&quot;The operation to perform (add, subtract, multiply, divide)&quot;),<br>   mcp.Enum(&quot;add&quot;, &quot;subtract&quot;, &quot;multiply&quot;, &quot;divide&quot;),<br>  ),<br>  mcp.WithNumber(&quot;x&quot;, mcp.Required(), mcp.Description(&quot;First number&quot;)),<br>  mcp.WithNumber(&quot;y&quot;, mcp.Required(), mcp.Description(&quot;Second number&quot;)),<br> )<br><br> s.AddTool(calculatorTool, func(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) {<br>  entry := logger.WithField(&quot;tool&quot;, &quot;calculate&quot;)<br>  op, ok := req.Params.Arguments[&quot;operation&quot;].(string)<br>  if !ok {<br>   err := errors.New(&quot;operation must be a string&quot;)<br>   entry.Error(err)<br>   return nil, err<br>  }<br>  x, ok := req.Params.Arguments[&quot;x&quot;].(float64)<br>  if !ok {<br>   err := errors.New(&quot;x must be a number&quot;)<br>   entry.Error(err)<br>   return nil, err<br>  }<br>  y, ok := req.Params.Arguments[&quot;y&quot;].(float64)<br>  if !ok {<br>   err := errors.New(&quot;y must be a number&quot;)<br>   entry.Error(err)<br>   return nil, err<br>  }<br><br>  result, err := calc(op, x, y)<br>  if err != nil {<br>   entry.WithError(err).Error(&quot;calculation failed&quot;)<br>   return nil, err<br>  }<br><br>  entry.WithFields(logrus.Fields{&quot;op&quot;: op, &quot;x&quot;: x, &quot;y&quot;: y, &quot;result&quot;: result}).Info(&quot;calculation succeeded&quot;)<br>  return mcp.NewToolResultText(fmt.Sprintf(&quot;%.2f&quot;, result)), nil<br> })<br>}<br><br>func calc(op string, x, y float64) (float64, error) {<br> switch op {<br> case &quot;add&quot;:<br>  return x + y, nil<br> case &quot;subtract&quot;:<br>  return x - y, nil<br> case &quot;multiply&quot;:<br>  return x * y, nil<br> case &quot;divide&quot;:<br>  if y == 0 {<br>   return 0, errors.New(&quot;cannot divide by zero&quot;)<br>  }<br>  return x / y, nil<br> default:<br>  return 0, errors.New(&quot;unsupported operation&quot;)<br> }<br>}<br><br>// ───────────────────────────────────────<br>// download_image tool + handler<br>// ───────────────────────────────────────<br>func registerDownloadImageTool(s *server.MCPServer) {<br> downloadTool := mcp.NewTool(&quot;download_image&quot;,<br>  mcp.WithDescription(&quot;Download an image from an HTTP/HTTPS URL and store it locally&quot;),<br>  mcp.WithString(&quot;url&quot;, mcp.Required(), mcp.Description(&quot;Direct URL to the image (http or https)&quot;)),<br> )<br><br> s.AddTool(downloadTool, func(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) {<br>  entry := logger.WithField(&quot;tool&quot;, &quot;download_image&quot;)<br>  raw, ok := req.Params.Arguments[&quot;url&quot;].(string)<br>  if !ok {<br>   err := errors.New(&quot;url must be a string&quot;)<br>   entry.Error(err)<br>   return nil, err<br>  }<br><br>  parsed, err := url.Parse(raw)<br>  if err != nil || (parsed.Scheme != &quot;http&quot; &amp;&amp; parsed.Scheme != &quot;https&quot;) {<br>   err := errors.New(&quot;url must start with http or https&quot;)<br>   entry.Error(err)<br>   return nil, err<br>  }<br>  httpReq, _ := http.NewRequestWithContext(ctx, http.MethodGet, parsed.String(), nil)<br>  resp, err := http.DefaultClient.Do(httpReq)<br>  if err != nil {<br>   entry.WithError(err).Error(&quot;failed to fetch url&quot;)<br>   return nil, fmt.Errorf(&quot;failed to fetch url: %w&quot;, err)<br>  }<br>  defer resp.Body.Close()<br><br>  if resp.StatusCode != http.StatusOK {<br>   err := fmt.Errorf(&quot;unexpected status code: %d&quot;, resp.StatusCode)<br>   entry.Error(err)<br>   return nil, err<br>  }<br>  if !strings.HasPrefix(resp.Header.Get(&quot;Content-Type&quot;), &quot;image/&quot;) {<br>   err := errors.New(&quot;content is not an image&quot;)<br>   entry.Error(err)<br>   return nil, err<br>  }<br><br>  base := filepath.Base(parsed.Path)<br>  if base == &quot;.&quot; || base == &quot;/&quot; {<br>   base = &quot;image&quot;<br>  }<br>  filename := fmt.Sprintf(&quot;%d_%s&quot;, time.Now().Unix(), base)<br>  outPath := filepath.Join(&quot;.&quot;, filename)<br><br>  out, err := os.Create(outPath)<br>  if err != nil {<br>   entry.WithError(err).Error(&quot;cannot create file&quot;)<br>   return nil, fmt.Errorf(&quot;cannot create file: %w&quot;, err)<br>  }<br>  defer out.Close()<br><br>  if _, err = io.Copy(out, resp.Body); err != nil {<br>   entry.WithError(err).Error(&quot;copy error&quot;)<br>   return nil, fmt.Errorf(&quot;copy error: %w&quot;, err)<br>  }<br><br>  entry.WithField(&quot;path&quot;, outPath).Info(&quot;image saved&quot;)<br>  return mcp.NewToolResultText(&quot;saved to &quot; + outPath), nil<br> })<br>}</pre><h4>🛠 Step 5: Build the Server</h4><pre>$ go build -o mcp_server</pre><h4>⚙️ Step 6: Create config.json</h4><pre>{<br>  &quot;mcpServers&quot;: {<br>    &quot;golang-mcp-server&quot;: {<br>      &quot;command&quot;: &quot;&lt;absolute path of your binary file&gt;/mcp_server&quot;,<br>      &quot;args&quot;: [],<br>      &quot;env&quot;: {}<br>    }<br>  }<br>}</pre><p>Replace ./mcp_server with your binary path if it’s different.</p><h3>🕹️ Play With Your Tools</h3><h4>🧮 Calculator</h4><p>Talk to it like:</p><pre>add 100 to 200  <br>subtract 50 from 600  <br>22 / 7<br>divide 9 by 0</pre><p>It parses the request → routes it to your tool → returns the answer or error.</p><h4>🖼️ Image Downloader</h4><p>Say:</p><pre>download image from https://example.com/cool-cat.jpg</pre><p>Boom. It saves the image locally. All clean.</p><h3>🧠 TL;DR</h3><ul><li><strong>MCP = Model Context Protocol</strong></li><li>It’s just JSON-RPC</li><li>Tools are exposed in schema form so LLMs can <em>call</em> them</li><li>You built a full MCP server in Go</li><li>And plugged it into a local LLM using Ollama</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c6258d37de85" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Craft with SageMaker: Single GPU, Multi-Model Mastery, and More Savings on AWS!]]></title>
            <link>https://plutoniumguy.medium.com/craft-with-sagemaker-single-gpu-multi-model-mastery-and-more-savings-on-aws-b084c9c4a7d7?source=rss-31cc3e8e2721------2</link>
            <guid isPermaLink="false">https://medium.com/p/b084c9c4a7d7</guid>
            <category><![CDATA[hugging-face]]></category>
            <category><![CDATA[deployment-pipelines]]></category>
            <category><![CDATA[sagemaker]]></category>
            <dc:creator><![CDATA[Amiya Mandal]]></dc:creator>
            <pubDate>Mon, 25 Sep 2023 05:20:47 GMT</pubDate>
            <atom:updated>2023-09-25T05:21:46.702Z</atom:updated>
            <content:encoded><![CDATA[<p>I am currently working on a use case in which we’ve deployed custom models on SageMaker, an AWS machine learning-supported service. The challenge we face is that, at any given time, most SageMaker endpoints remain idle. To break it down:</p><ol><li>We have three custom models. The first model performs NER using dslim/bert-base-NER. The second conducts summarization using google/pegasus-xsum.</li><li>Following the official HuggingFace documentation, we deploy these deep learning models, as seen <a href="https://huggingface.co/docs/sagemaker/inference">here</a>.</li><li>This results in 2 distinct SageMaker endpoints. These consume considerable AWS credits, especially when opting for GPU instances, given that deep learning models run faster on GPUs compared to CPUs.</li></ol><p>Despite extensive research, I’ve been unable to deploy multiple deep learning models on a single GPU within SageMaker to reduce operational costs. I got some work around.</p><p><strong>Let’s build it :-</strong></p><p>Folder structure for multi-model deployment</p><pre>common_model<br>├── code<br>│   └── inference.py<br>├── ner_model_custom_bert_base_ner<br>│   ├── config.json<br>│   ├── optimizer.pt<br>│   ├── pytorch_model.bin<br>│   ├── rng_state.pth<br>│   ├── scheduler.pt<br>│   ├── special_tokens_map.json<br>│   ├── tokenizer_config.json<br>│   ├── tokenizer.json<br>│   ├── trainer_state.json<br>│   └── training_args.bin<br>└── custom_model_pegasus_xsum<br>    ├── config.json<br>    ├── generation_config.json<br>    ├── pytorch_model.bin<br>    ├── special_tokens_map.json<br>    ├── spiece.model<br>    ├── tokenizer_config.json<br>    └── tokenizer.json</pre><p>Now lets creater most important file which is <strong><em>inference.py</em></strong></p><p>Lets import the important dependency</p><pre>import torch<br>from transformers import AutoModelForTokenClassification<br>from transformers import AutoTokenizer, AutoModelForSeq2SeqLM<br>from transformers import pipeline<br><br>device = torch.device(&#39;cuda:0&#39; if torch.cuda.is_available() else &#39;cpu&#39;)<br><br>os.environ[&quot;TOKENIZERS_PARALLELISM&quot;] = &quot;false&quot;</pre><p>There are three crucial functions that orchestrate the entire process:</p><ol><li>freeze_model: This function freezes the weights of the model.</li><li>model_fn: This function initializes the model.</li><li>predict_fn: This function is invoked when the SageMaker endpoint is accessed from any service.</li></ol><pre>def freeze_model(model):<br>    for param in model.parameters():<br>        param.requires_grad = False<br><br>NER_MODEL_PATH = &quot;ner_model_custom_bert_base_ner/&quot;<br>SUMMARY_MODEL_PATH = &quot;custom_model_pegasus_xsum/&quot;<br><br><br>def model_fn(_):<br>    tokenizer_summary = AutoTokenizer.from_pretrained(SUMMARY_MODEL_PATH, local_files_only=True)<br>    model_summary = AutoModelForSeq2SeqLM.from_pretrained(SUMMARY_MODEL_PATH, local_files_only=True)<br>    model_summary = model_summary.to(device)<br>    # Freeze the model weights before tokenization<br>    freeze_model(model_summary)<br><br>    tokenizer_ner = AutoTokenizer.from_pretrained(NER_PATH, local_files_only=True)<br>    model_ner = AutoModelForTokenClassification.from_pretrained(NER_PATH, local_files_only=True)<br>    model_ner = model_ner.to(device)<br>    freeze_model(model_ner)<br><br>    return tokenizer_summary, model_summary, tokenizer_ner, model_ner<br><br><br>def predict_fn(data, model_and_tokenizer):<br>    tokenizer_summary, model_summary, tokenizer_ner, model_ner = model_and_tokenizer<br><br>    if data[&quot;model&quot;] == &quot;summary&quot;:<br>        sentence = data[&quot;inputs&quot;]<br>        max_length = int(data[&quot;max_length&quot;])<br>        min_length = int(data[&quot;min_length&quot;])<br>        try:<br>            num_beams = int(data[&quot;num_beams&quot;])<br>        except:<br>            num_beams = 4<br>        params = {<br>            &#39;max_length&#39;: max_length,<br>            &#39;min_length&#39;: min_length,<br>            &#39;repetition_penalty&#39;: 1.05,<br>            &#39;early_stopping&#39;: True,<br>            &#39;num_beams&#39;: num_beams<br>        }<br>        try:<br>            summary_val= pipeline(&quot;text2text-generation&quot;, model=model_summary, tokenizer=tokenizer_summary, device=device)<br>            rez = summary_val(sentence, **params)<br>            return {&quot;response&quot;: rez[-1][&quot;generated_text&quot;]}<br>        except Exception as e:<br>            logging.error(f&quot;{e}&quot;)<br>            return {&quot;response&quot;: None}<br>    elif data[&quot;model&quot;] == &quot;ner&quot;:<br>        sentences = data[&quot;inputs&quot;]<br>        nlp = pipeline(&#39;ner&#39;, model=model_ner, tokenizer=tokenizer_ner, aggregation_strategy=&quot;simple&quot;, device=device)<br>        p1 = nlp(sentences)<br>        merged_list = p1.copy()<br>        return merged_list</pre><p><strong>Now lets deploy all the code:-</strong></p><ul><li>Import all important packages</li></ul><pre>import sagemaker<br>from sagemaker.huggingface import HuggingFaceModel <br>from sagemaker.serializers import IdentitySerializer<br>from sagemaker.deserializers import JSONDeserializer</pre><ul><li>Now we will create <strong>tar.gz</strong></li></ul><pre>cd common_model/ &amp;&amp; tar -czvf ../common_model.tar.gz .</pre><ul><li>Now lets upload to s3</li></ul><pre>aws s3 cp common_model.tar.gz s3://temp_bucket/</pre><ul><li>Now we will create few objects of some class</li></ul><pre>huggingface_model = HuggingFaceModel(<br>    model_data=&quot;s3://temp_bucket/common_model.tar.gz&quot;,  # path to your trained SageMaker model<br>    role=role,                                            # IAM role with permissions to create an endpoint<br>    transformers_version=&quot;4.26&quot;,                           # Transformers version used<br>    pytorch_version=&quot;1.13&quot;,                                # PyTorch version used<br>    py_version=&#39;py39&#39;,<br>)</pre><ul><li>Now it time to deploy</li></ul><pre>predictor = huggingface_model.deploy(<br>    initial_instance_count=1,<br>    instance_type=&quot;ml.g4dn.xlarge&quot;, # change as per your requirement<br>    serializer=IdentitySerializer(content_type=&quot;application/json&quot;),<br>    deserializer=JSONDeserializer(),<br>    endpoint_name=&quot;common-model-summary-and-ner&quot;,<br>)</pre><ul><li>Now its deployed</li></ul><p><strong>Time to test :-</strong></p><pre>import json<br><br>data = {<br>   &quot;inputs&quot;: &quot;&lt;summary you want to generate&gt;&quot;,<br>    &quot;model&quot;:&quot;summary&quot;,<br>    &quot;max_length&quot;:max_length,<br>    &quot;min_length&quot;: min_length,<br>    &quot;num_beams&quot;: 8<br>}<br><br>predictor.predict(json.dumps(data))<br><br># response :-<br># {&#39;response&#39;: &#39;&lt;summary&gt;&#39;}<br><br>data = {<br>   &quot;inputs&quot;: &quot;&lt;sent to generate ner&gt;&quot;,<br>    &quot;model&quot;:&quot;ner&quot;,<br>}<br><br>predictor.predict(json.dumps(data))<br><br># response:-<br># [{&#39;entity_group&#39;: &#39;CARDINAL&#39;,<br>#   &#39;score&#39;: 0.4931609034538269,<br>#   &#39;word&#39;: &#39;&lt;some value&gt;&#39;,<br>#   &#39;start&#39;: 14,<br>#   &#39;end&#39;: 16},<br>#  {&#39;entity_group&#39;: &#39;CARDINAL&#39;,<br>#   &#39;score&#39;: 0.9993178844451904,<br>#   &#39;word&#39;: &#39;&lt;some value&gt;&#39;,<br>#   &#39;start&#39;: 48,<br>#   &#39;end&#39;: 52},<br>#  {&#39;entity_group&#39;: &#39;PERSON&#39;, &#39;word&#39;: &#39;&lt;some value&gt;&#39;, &#39;start&#39;: 6, &#39;end&#39;: 13}]</pre><p>Now its done</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b084c9c4a7d7" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>