Close Menu
    Trending
    • OpenAIs nya webbläsare ChatGPT Atlas
    • Creating AI that matters | MIT News
    • Scaling Recommender Transformers to a Billion Parameters
    • Hidden Gems in NumPy: 7 Functions Every Data Scientist Should Know
    • Is RAG Dead? The Rise of Context Engineering and Semantic Layers for Agentic AI
    • ChatGPT Gets More Personal. Is Society Ready for It?
    • Why the Future Is Human + Machine
    • Why AI Is Widening the Gap Between Top Talent and Everyone Else
    ProfitlyAI
    • Home
    • Latest News
    • AI Technology
    • Latest AI Innovations
    • AI Tools & Technologies
    • Artificial Intelligence
    ProfitlyAI
    Home » MCP Client Development with Streamlit: Build Your AI-Powered Web App
    Artificial Intelligence

    MCP Client Development with Streamlit: Build Your AI-Powered Web App

    ProfitlyAIBy ProfitlyAIJuly 21, 2025No Comments9 Mins Read
    Share Facebook Twitter Pinterest LinkedIn Tumblr Reddit Telegram Email
    Share
    Facebook Twitter LinkedIn Pinterest Email


    In “Model Context Protocol (MCP) Tutorial: Build Your First MCP Server in 6 Steps”, we launched the MCP structure and explored MCP servers intimately. We are going to proceed our MCP exploration on this tutorial, by constructing an interactive MCP shopper interface utilizing Streamlit. The principle distinction between an MCP server and an MCP shopper is that MCP server offers functionalities by connecting to a various vary of instruments and assets, whereas MCP shopper leverages these functionalities via an interface. Streamlit, a light-weight Python library for data-driven interactive net functions growth, accelerates the event cycle and abstracts away frontend frameworks, making it an optimum selection for speedy prototyping and the streamlined deployment of AI-powered instruments. Subsequently, we’re going to use Streamlit to assemble our MCP shopper person interface via a minimal setup, whereas specializing in connecting to distant MCP servers for exploring various AI functionalities.

    Challenge Overview

    Create an interactive net app prototype the place customers can enter their subjects of curiosity and select between two MCP servers—DeepWiki and HuggingFace—that present related assets. DeepWiki focuses on summarizing codebases and GitHub repositories, whereas the HuggingFace MCP server offers suggestions of open-source datasets and fashions associated to the person’s subjects. The picture under shows the net app’s output for the subject “sentiment evaluation”.

    To develop the Streamlit MCP shopper, we’ll break it down into the next steps:

    • Set Up Growth Surroundings
    • Initialize Streamlit App Format
    • Get Consumer Inputs
    • Hook up with Distant MCP Servers
    • Generate Mannequin Responses
    • Run the Streamlit App

    Set Up Growth Surroundings

    Firstly, let’s arrange our mission listing utilizing a easy construction.

    mcp_streamlit_client/
    ├── .env                  # Surroundings variables (API keys)
    ├── README.md             # Challenge documentation
    ├── necessities.txt      # Required libraries and dependencies
    └── app.py                # Essential Streamlit utility

    Then set up obligatory libraries – we want streamlit for constructing the net interface and openai for interacting with OpenAI’s API that helps MCP.

    pip set up streamlit openai

    Alternatively, you possibly can create a necessities.txt file to specify the library variations for reproducible installations by working:

    pip set up -r necessities.txt

    Secondly, safe your API Keys utilizing setting variables. When working with LLM suppliers like OpenAI, you’ll need to arrange an API key. To maintain this key confidential, the perfect observe is to make use of setting variables to load the API key and keep away from exhausting coding it straight into your script, particularly should you plan to share your code or deploy your utility. To do that, add your API keys within the .env file utilizing the next format. We will even want Hugging Face API token to entry its distant MCP server.

    OPENAI_API_KEY="your_openai_api_key_here" 
    HF_API_KEY="your_huggingface_api_key_here" 

    Now, within the script app.py, you possibly can load these variables into your utility’s setting utilizing load_dotenv() from the dotenv library. This perform reads the key-value pairs out of your .env file and makes them accessible through os.getenv().

    from dotenv import load_dotenv
    import os
    
    load_dotenv() 
    
    # entry HuggingFace API key utilizing os.getenv()
    HF_API_KEY = os.getenv('HF_API_KEY')

    Join MCP Server and Consumer

    Earlier than diving into MCP shopper growth, let’s perceive the fundamentals of building an MCP server-client connection. With the rising recognition of MCP, an growing variety of LLM suppliers now assist MCP shopper implementation. For instance, OpenAI gives an easy initialization technique utilizing the code under.

    from openai import OpenAI
    
    shopper = OpenAI()
    Additional Studying:

    The article “For Client Developers” offers the instance to arrange an Anthropic MCP shopper, which is barely sophisticated but additionally extra sturdy because it allows higher session and useful resource administration.

    To attach the shopper to an MCP server, you’ll must implement a connection technique that takes both a server script path (for native MCP servers) or URL (for distant MCP servers) because the enter. Native MCP servers are packages that run in your native machine, whereas distant MCP servers are deployed on-line and accessible via a URL. For instance under, we’re connecting to a distant MCP server “DeepWiki” via “https://mcp.deepwiki.com/mcp”.

    response = shopper.responses.create(
        mannequin="gpt-4.1",
        instruments=[
            {
                "type": "mcp",
                "server_label": "deepwiki",
                "server_url": "https://mcp.deepwiki.com/mcp",
                "require_approval": "never",
            },
        ]
    )
    Additional Readings:

    It’s also possible to discover different MCP server choices on this complete “Remote MCP Servers Catalogue” in your particular wants. The article “For Client Developers” additionally offers instance to attach native MCP servers.

    Construct the Streamlit MCP Consumer

    Now that we perceive the basics of building connections between MCP shoppers and servers, we’ll encapsulate this performance inside an internet interface for enhanced person expertise. This net app is designed with modularity in thoughts, composed of a number of parts applied utilizing Streamlit strategies, similar to st.radio(), st.button(), st.information(), st.title() and st.text_area().

    1. Initialize Your Streamlit Web page

    We are going to begin with initialize_page() perform that units the web page icon and title, and makes use of structure="centered" to make sure the general net app structure to be aligned within the heart. This perform returns a column object beneath the web page title the place we’ll place widgets proven within the following steps.

    import streamlit as st
    
    def initialize_page():
        """Initialize the Streamlit web page configuration and structure"""
        st.set_page_config(
            page_icon="🤖", # A robotic emoji because the web page icon
            structure="centered" # Heart the content material on the web page
        )
        st.title("Streamlit MCP Consumer") # Set the principle title of the app
    
        # Return a column object which can be utilized to position widgets
        return st.columns(1)[0]

    2. Get Consumer Inputs

    The get_user_input() perform permits customers to supply their enter, by making a textual content space widget utilizing st.text_area(). The top parameter ensures the enter field is sufficiently sized, and the placeholder textual content prompts the person with particular directions.

    def get_user_input(column):
        """Deal with transcript enter strategies and return the transcript textual content"""
    
        user_text = column.text_area(
            "Please enter the subjects you’re fascinated with:",
            top=100,
            placeholder="Kind it right here..."
        )
    
        return user_text

    3. Hook up with MCP Servers

    The create_mcp_server_dropdown() perform facilitates the pliability to select from a spread of MCP servers. It defines a dictionary of accessible MCP servers, mapping a label (like “deepwiki” or “huggingface”) to its corresponding server URL. Streamlit’s st.radio() widget shows these choices as radio buttons for customers to select from. This perform then returns each the chosen server’s label and its URL, feeding into the following step to generate responses.

    def create_mcp_server_dropdown():
        # Outline an inventory of MCP servers with their labels and URLs
        mcp_servers = {
            "deepwiki": "https://mcp.deepwiki.com/mcp",
            "huggingface": "https://huggingface.co/mcp"
        }
    
        # Create a radio button for choosing the MCP server
        selected_server = st.radio(
            "Choose MCP Server",
            choices=listing(mcp_servers.keys()), 
            assist="Select the MCP server you wish to hook up with"
        )
    
        # Get the URL comparable to the chosen server
        server_url = mcp_servers[selected_server]
    
        return selected_server, server_url

    4. Generate Responses

    Earlier we see how one can use shopper.responses.create() as a normal solution to generate responses. The generate_response() perform under extends this by passing a number of customized parameters:

    • mannequin: select the LLM mannequin that matches your funds and function.
    • instruments: decided by the person chosen MCP server URL. On this case, since Hugging Face server requires person authentication, we additionally specify the API key within the software configuration and show an error message when the secret is not discovered.
    • enter: this combines person’s question and tool-specific directions
      to supply clear context for the immediate.

    The person’s enter is then despatched to the LLM, which leverages the chosen MCP server as an exterior software to meet the request. And show the responses utilizing the Streamlit information widget st.information(). In any other case, it is going to return an error message utilizing st.error() when no responses are produced.

    from openai import OpenAI
    import os
    
    load_dotenv()
    HF_API_KEY = os.getenv('HF_API_KEY') 
    
    def generate_response(user_text, selected_server, server_url):
        """Generate response utilizing OpenAI shopper and MCP instruments"""
        shopper = OpenAI() 
    
        strive:
            mcp_tool = {
                "kind": "mcp",
                "server_label": selected_server, 
                "server_url": server_url,      
                "require_approval": "by no means",   
            }
    
            if selected_server == 'huggingface':
                if HF_API_KEY:
                    mcp_tool["headers"] = {"Authorization": f"Bearer {HF_API_KEY}"}
                else:
                    st.warning("Hugging Face API Key not present in .env. Some functionalities is likely to be restricted.")
                prompt_text = f"Listing some assets related to this subject: {user_text}?"
            else:
                prompt_text = f"Summarize codebase contents related to this subject: {user_text}?"
    
            response = shopper.responses.create(
                mannequin="gpt-3.5-turbo", 
                instruments=[mcp_tool],      
                enter=prompt_text
            )
    
            st.information(
                f"""
                **Response:**
                {response.output_text}
                """
            )
            return response
    
        besides Exception as e:
            st.error(f"Error producing response: {str(e)}") 
            return None

    5. Outline the Essential Perform

    The ultimate step is to create a most important() perform that chains all operations collectively. This perform sequentially calls initialize_page(), get_user_input(), and create_mcp_server_dropdown() to arrange the UI and acquire person inputs. It then creates a situation to set off generate_response() when the person clicks st.button("Generate Response"). Upon clicking, the perform checks if person enter exists, shows a spinner with st.spinner() to indicate progress, and returns the response. If no enter is supplied, the app shows a warning message as a substitute of calling generate_response(), stopping pointless token utilization and further prices.

    def most important():
        # 1. Initialize the web page structure
        main_column = initialize_page()
    
        # 2. Get person enter for the subject
        user_text = get_user_input(main_column)
    
        # 3. Enable person to pick out the MCP server
        with main_column: # Place the radio buttons inside the principle column
            selected_server, server_url = create_mcp_server_dropdown()
    
        # 4. Add a button to set off the response era
        if st.button("Generate Response", key="generate_button"):
            if user_text:
                with st.spinner("Producing response..."): 
                    generate_response(user_text, selected_server, server_url)
            else:
                st.warning("Please enter a subject first.")

    Run Streamlit Software

    Lastly, a normal Python script entry level ensures that our most important perform is executed when the script is run.

    if __name__ == "__main__":
        most important()

    Open your terminal or command immediate, navigate to the listing the place you saved the file, and run:

    streamlit run app.py

    In case you are growing your app domestically, an area Streamlit server will spin up and your app will open in a brand new tab in your default net browser. Alternatively, in case you are growing in a cloud setting, similar to AWS JupyterLab, change the default URL with this format: https://<APP_ID>.studio.<REGION>.sagemaker.aws/jupyterlab/default/proxy/8501/. You could discover the publish “Build Streamlit apps in Amazon SageMaker AI Studio” useful.

    Lastly, you will discover the code in our GitHub repository “mcp-streamlit-client” and discover your Streamlit MCP shopper by making an attempt out completely different subjects.


    Take-Dwelling Message

    In our earlier article, we launched the MCP structure and centered on the MCP server. Constructing on this basis, we now discover implementing an MCP shopper with Streamlit to boost the software calling capabilities of distant MCP servers. This information offers important steps—from organising your growth setting and securing API keys, dealing with person enter, connecting to distant MCP servers, and displaying AI-generated responses. To arrange this utility for manufacturing, contemplate these subsequent steps:

    • Asynchronous processing of a number of shopper requests
    • Caching mechanisms for quicker response instances
    • Session state administration
    • Consumer authentication and entry administration



    Source link

    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
    Previous ArticleMIT Learn offers “a whole new front door to the Institute” | MIT News
    Next Article Hands‑On with Agents SDK: Your First API‑Calling Agent
    ProfitlyAI
    • Website

    Related Posts

    Artificial Intelligence

    Creating AI that matters | MIT News

    October 21, 2025
    Artificial Intelligence

    Scaling Recommender Transformers to a Billion Parameters

    October 21, 2025
    Artificial Intelligence

    Hidden Gems in NumPy: 7 Functions Every Data Scientist Should Know

    October 21, 2025
    Add A Comment
    Leave A Reply Cancel Reply

    Top Posts

    A practical guide to modern document parsing

    September 5, 2025

    Understanding Random Forest using Python (scikit-learn)

    May 16, 2025

    OpenAI’s New Report Details How We Use ChatGPT at Work

    September 30, 2025

    Python Can Now Call Mojo | Towards Data Science

    September 21, 2025

    Manus AI agentplattformen släpper version 1.5

    October 20, 2025
    Categories
    • AI Technology
    • AI Tools & Technologies
    • Artificial Intelligence
    • Latest AI Innovations
    • Latest News
    Most Popular

    Mozilla Firefox planerar att marknadsföra sökmotorn Perplexity

    May 19, 2025

    China built hundreds of AI data centers to catch the AI boom. Now many stand unused.

    April 3, 2025

    What the Most Detailed Peer-Reviewed Study on AI in the Classroom Taught Us

    May 20, 2025
    Our Picks

    OpenAIs nya webbläsare ChatGPT Atlas

    October 22, 2025

    Creating AI that matters | MIT News

    October 21, 2025

    Scaling Recommender Transformers to a Billion Parameters

    October 21, 2025
    Categories
    • AI Technology
    • AI Tools & Technologies
    • Artificial Intelligence
    • Latest AI Innovations
    • Latest News
    • Privacy Policy
    • Disclaimer
    • Terms and Conditions
    • About us
    • Contact us
    Copyright © 2025 ProfitlyAI All Rights Reserved.

    Type above and press Enter to search. Press Esc to cancel.