← docs

Use Bazaar MCP Tools with LangChain

Connect your LangChain agents to Agent Bazaar's metered MCP tool marketplace. Every tool call is priced, metered, and receipted — your agent pays only for what it uses.

Prerequisites

1. Install Dependencies

pip install langchain langchain-openai mcp

The mcp package provides the MCP client that connects to Bazaar's proxy endpoint.

2. Set Environment Variables

export NOUI_API_KEY="bz_your_key_here"
export OPENAI_API_KEY="sk-..."   # or any LLM provider

Or use a .env file with python-dotenv.

3. Connect to Bazaar via MCP

Use the MCP client to connect to Bazaar's SSE proxy endpoint, then convert the discovered tools into LangChain-compatible tools:

import os
import asyncio
import json
from mcp import ClientSession
from mcp.client.sse import sse_client
from langchain_core.tools import StructuredTool
from langchain_openai import ChatOpenAI
from langchain.agents import AgentExecutor, create_tool_calling_agent
from langchain_core.prompts import ChatPromptTemplate

BAZAAR_URL = "https://noui.bot/api/mcp/sse"
API_KEY = os.environ["NOUI_API_KEY"]


async def get_bazaar_tools(session: ClientSession) -> list[StructuredTool]:
    """Discover Bazaar MCP tools and wrap them as LangChain tools."""
    tools_result = await session.list_tools()
    lc_tools = []

    for tool in tools_result.tools:
        # Capture tool name for closure
        tool_name = tool.name

        async def _call(session=session, name=tool_name, **kwargs):
            result = await session.call_tool(name, arguments=kwargs)
            return json.dumps([c.text for c in result.content])

        lc_tools.append(
            StructuredTool.from_function(
                func=lambda **kw: asyncio.get_event_loop().run_until_complete(
                    _call(**kw)
                ),
                coroutine=lambda **kw: _call(**kw),
                name=tool.name,
                description=tool.description or "",
                # Accept any kwargs — Bazaar tools define their own schemas
            )
        )
    return lc_tools


async def main():
    headers = {"Authorization": f"Bearer {API_KEY}"}

    async with sse_client(BAZAAR_URL, headers=headers) as (read, write):
        async with ClientSession(read, write) as session:
            await session.initialize()

            # Convert MCP tools → LangChain tools
            tools = await get_bazaar_tools(session)
            print(f"Loaded {len(tools)} Bazaar tools")

            # Build a LangChain agent
            llm = ChatOpenAI(model="gpt-4o", temperature=0)
            prompt = ChatPromptTemplate.from_messages([
                ("system", "You are a helpful agent with access to "
                           "Bazaar MCP tools. Use them when needed."),
                ("human", "{input}"),
                ("placeholder", "{agent_scratchpad}"),
            ])

            agent = create_tool_calling_agent(llm, tools, prompt)
            executor = AgentExecutor(agent=agent, tools=tools, verbose=True)

            result = await executor.ainvoke({
                "input": "Check the platform stats on noui.bot"
            })
            print(result["output"])


asyncio.run(main())

4. How Billing Works

Every tool call through Bazaar is metered transparently:

What happens on each tool call:

  1. Your agent calls a Bazaar tool via MCP
  2. Bazaar checks your balance and the tool's per-call price
  3. The tool executes and returns results
  4. Your balance is debited and a receipt is issued
# Check your balance anytime
curl https://noui.bot/api/v1/bazaar/balance \
  -H "Authorization: Bearer bz_your_key"

# View receipts
curl https://noui.bot/api/v1/bazaar/usage/summary \
  -H "Authorization: Bearer bz_your_key"

5. Production Tips

Connection Reuse

Keep the MCP session open across multiple agent runs. The SSE connection is persistent — reconnecting on every call adds latency.

Error Handling

Bazaar returns structured errors for insufficient balance, rate limits, and provider failures. Wrap tool calls in try/except for graceful fallback.

Cost Controls

Set a per-session budget by checking balance before and after agent runs. Tools expose their price in the MCP tool metadata.

See Also