# Beyond Code Generation: Building AI Agent Workflows with Claude Code, MCP and Python

# Beyond Code Generation: Building AI Agent Workflows with Claude Code, MCP and Python

*How to turn Python scripts into reusable AI tools and build intelligent workflows that go beyond conventional coding assistance.*

Most developers initially use AI coding assistants to generate functions, fix bugs, explain code or build applications.

That's useful, but what interests me more is what happens when we connect these assistants to existing tools, APIs, databases and custom Python applications.

Over the past few years, my work has expanded from traditional SEO and web development into LLMs, Retrieval-Augmented Generation (RAG), AI agents and workflow automation. During this transition, I've become increasingly interested in building tools that AI systems can operate directly rather than simply generating instructions for humans.

Consider a technical SEO audit.

Instead of asking an AI assistant to explain how to audit a website, what if it could actually access the website, extract its metadata, check its technical configuration, analyze the findings and recommend improvements?

This is where Claude Code, Model Context Protocol (MCP) and Python can work together.

In this article, we'll explore the architecture behind this approach and build a simple MCP-powered SEO auditing workflow.

## TL;DR

- Claude Code can interact with external tools through MCP.
- MCP provides a standardized interface between AI applications and external capabilities.
- Python can handle deterministic operations such as website analysis, data extraction and API requests.
- AI agents can use the resulting information to plan tasks, investigate problems and generate recommendations.
- You don't necessarily need LangChain, LangGraph or n8n to build your first tool-enabled AI workflow.

## 1. Why Move Beyond AI Code Generation?

A conventional coding assistant workflow looks something like this:

User Request → AI Model → Generated Code → Manual Execution → Result

For many development tasks, this is sufficient.

However, business workflows often involve multiple systems and repeated operations.

Imagine an SEO professional conducting a website audit. The process might involve checking HTTP responses, inspecting metadata, validating structured data, analyzing internal links and comparing historical performance.

Generating Python code for every individual operation is inefficient when reusable tools can perform those operations directly.

A tool-enabled workflow looks different:

User Objective → AI Agent → Tool Selection → Tool Execution → Result Analysis → Recommendations

The AI application becomes responsible for coordinating available tools, while individual tools perform specific operations.

This separation of responsibilities is particularly useful when developing reliable automation systems.

## 2. What Is Model Context Protocol?

Model Context Protocol, commonly referred to as MCP, is an open protocol that allows AI applications to connect to external tools and information sources through a standardized interface.

Rather than creating a completely different integration for every AI application, developers can expose capabilities through an MCP server.

An MCP server can provide three important types of capabilities.

**Tools:** Functions that an AI application can invoke to perform operations.

**Resources:** Contextual information that an application can retrieve, such as documents or configuration data.

**Prompts:** Reusable prompt templates that support predefined interactions.

For example, an SEO MCP server could expose tools named:

- audit_metadata
- check_robots
- analyze_internal_links
- validate_schema
- get_search_performance

An AI application can discover these tools, understand their expected parameters and invoke them when appropriate.

The model does not need to know every implementation detail of the underlying Python functions.

That is one of the practical advantages of MCP.

## 3. Understanding the Architecture

Before writing any code, let's establish a simple architecture.

```mermaid
flowchart TD
    A[User Objective] --> B[Claude Code]
    B --> C[MCP Client]
    C --> D[Python MCP Server]
    D --> E[Website Analysis Tools]
    D --> F[Document Retrieval]
    D --> G[External APIs]
    E --> H[Structured Results]
    F --> H
    G --> H
    H --> B
    B --> I[Analysis and Recommendations]
```

Each component has a specific responsibility.

Claude Code interprets the user's objective and decides which available tools may help complete the task.

The MCP client handles communication with the configured MCP server.

The Python server exposes functions that perform actual operations.

External websites, APIs and databases provide the underlying information.

Claude then interprets the returned results and generates a useful response.

This architecture can be extended without rebuilding the entire application.

For example, adding Google Search Console integration could involve creating another Python tool and exposing it through the existing MCP server.

## 4. Building a Simple SEO MCP Server

Let's create a small Python MCP server capable of performing two operations:

1. Extracting basic SEO metadata from a website.
2. Checking the website's robots.txt file.

The objective is not to build a complete SEO crawler. It is to demonstrate how existing Python functionality can become accessible to an AI application.

### Prerequisites

You will need:

- Python 3.10 or newer
- Claude Code installed and configured
- VS Code or another code editor
- Basic knowledge of Python
- An internet connection

The following example uses the MCP Python SDK v1 API.

Create a project directory.

```bash
mkdir seo-mcp-agent
cd seo-mcp-agent
python -m venv .venv
```

Activate the virtual environment.

For Windows PowerShell:

```powershell
.\.venv\Scripts\Activate.ps1
```

For Linux or macOS:

```bash
source .venv/bin/activate
```

Install the required dependencies.

```bash
pip install "mcp>=1.28,<2" requests beautifulsoup4
```

Your initial project structure should look like this:

```text
seo-mcp-agent/
├── .venv/
├── server.py
└── requirements.txt
```

Add the dependencies to `requirements.txt`:

```text
mcp>=1.28,<2
requests
beautifulsoup4
```

## 5. Creating the Python Tools

Create a file named `server.py`.

```python
from mcp.server.fastmcp import FastMCP
from bs4 import BeautifulSoup
from urllib.parse import urlsplit, urlunsplit
import requests

mcp = FastMCP("SEO Audit Tools")

ALLOWED_HOSTS = {"example.com", "www.example.com"}

HEADERS = {
    "User-Agent": "SEO-MCP-Audit/1.0"
}


def fetch_page(url: str) -> requests.Response:
    parsed = urlsplit(url)

    if (
        parsed.scheme != "https"
        or parsed.hostname not in ALLOWED_HOSTS
        or parsed.username
        or parsed.password
        or parsed.port not in (None, 443)
    ):
        raise ValueError("URL is not permitted.")

    response = requests.get(
        url,
        headers=HEADERS,
        timeout=15,
        allow_redirects=False
    )

    if 300 <= response.status_code < 400:
        raise ValueError(
            "Redirect detected. Review the destination."
        )

    return response


@mcp.tool()
def audit_metadata(url: str) -> dict:
    """Extract basic SEO metadata from an approved website."""

    try:
        response = fetch_page(url)
        response.raise_for_status()

        soup = BeautifulSoup(
            response.text,
            "html.parser"
        )

        title = soup.find("title")

        description = soup.find(
            "meta",
            attrs={"name": "description"}
        )

        canonical = soup.find(
            "link",
            rel="canonical"
        )

        robots = soup.find(
            "meta",
            attrs={"name": "robots"}
        )

        headings = [
            h.get_text(strip=True)
            for h in soup.find_all("h1")
        ]

        return {
            "url": url,
            "status_code": response.status_code,
            "title": title.get_text(strip=True)
            if title else None,
            "meta_description": description.get("content")
            if description else None,
            "canonical": canonical.get("href")
            if canonical else None,
            "meta_robots": robots.get("content")
            if robots else None,
            "h1_count": len(headings),
            "h1_headings": headings
        }

    except (requests.RequestException, ValueError) as e:
        return {"error": str(e)}


@mcp.tool()
def check_robots(url: str) -> dict:
    """Retrieve robots.txt from an approved website."""

    try:
        parsed = urlsplit(url)

        robots_url = urlunsplit((
            parsed.scheme,
            parsed.netloc,
            "/robots.txt",
            "",
            ""
        ))

        response = fetch_page(robots_url)

        return {
            "url": robots_url,
            "status_code": response.status_code,
            "content": response.text[:10000]
            if response.status_code == 200 else None
        }

    except (requests.RequestException, ValueError) as e:
        return {"error": str(e)}


if __name__ == "__main__":
    mcp.run(transport="stdio")
```

There are a few things worth understanding about this implementation.

The `@mcp.tool()` decorator exposes a Python function as an MCP tool.

The type annotations and docstrings help describe the tool's interface to the AI application.

The functions return structured data instead of generating a lengthy natural-language report.

This is intentional. Python is responsible for collecting evidence, while the AI application is responsible for interpreting it.

I've also included an explicit domain allowlist and disabled automatic redirects. Before testing your own website, add its authorized hostname to `ALLOWED_HOSTS`.

These are basic safeguards for a local demonstration, not a complete security implementation for a publicly accessible service.

## 6. Connecting the MCP Server to Claude Code

Once the Python server is ready, register it with Claude Code.

From your project directory, with the virtual environment activated, run:

```bash
claude mcp add --transport stdio seo-audit -- python server.py
```

For a more reliable configuration, particularly on Windows, use the absolute paths to your virtual environment's Python executable and the server script.

You can also configure the server through a project-level `.mcp.json` file.

```json
{
  "mcpServers": {
    "seo-audit": {
      "type": "stdio",
      "command": "python",
      "args": ["server.py"]
    }
  }
}
```

This assumes Python resolves to the environment containing your dependencies and the server starts from the correct project directory. Absolute paths can avoid configuration problems.

Check the registered MCP servers:

```bash
claude mcp list
```

Start Claude Code:

```bash
claude
```

Inside the session, use:

```text
/mcp
```

You should be able to inspect the configured server and its available capabilities once the connection is established.

## 7. Running Your First AI-Powered SEO Audit

Instead of asking Claude to generate an SEO checklist, provide an objective that requires it to use the MCP tools.

For example:

> Use the SEO Audit Tools MCP server to inspect https://example.com. Extract its metadata, check robots.txt, identify observable technical issues and provide prioritized recommendations. Do not invent findings that are not supported by the tool outputs.

The workflow may involve the following steps:

- Claude identifies the available SEO tools.
- It invokes `audit_metadata`.
- It invokes `check_robots`.
- The Python server retrieves the requested information.
- Claude evaluates the returned data.
- It prepares a report based on the available evidence.

The important distinction is that the AI application is working with collected information rather than relying entirely on its general knowledge of SEO.

### Illustrative tool output

```json
{
  "url": "https://example.com",
  "status_code": 200,
  "title": "Example Domain",
  "meta_description": null,
  "canonical": null,
  "meta_robots": null,
  "h1_count": 1,
  "h1_headings": [
    "Example Domain"
  ]
}
```

This is an illustrative output, not a recorded live execution.

From the returned information, Claude could identify the absence of a meta description and canonical tag.

However, it should not automatically classify every missing element as a critical SEO problem. The significance of a finding depends on the page's purpose and technical context.

That is where reasoning becomes useful.

## 8. Turning the MCP Server into an Agentic Workflow

The previous example demonstrates tool usage, but a more capable agentic system can also decide whether additional investigation is required.

Suppose the metadata audit returns an HTTP error.

An agentic workflow could determine that analyzing headings and metadata is no longer useful until the accessibility problem has been investigated.

If the page loads successfully but important content is missing from the initial HTML, the agent might select a browser rendering tool.

If duplicate pages are discovered, it might invoke a canonical comparison tool.

A more advanced workflow could look like this:

```mermaid
flowchart TD
    A[Website URL] --> B[Initial SEO Audit]
    B --> C{Page Accessible?}
    C -->|No| D[Investigate HTTP Errors]
    C -->|Yes| E[Analyze HTML]
    E --> F{More Evidence Needed?}
    F -->|Yes| G[Run Additional Tools]
    G --> E
    F -->|No| H[Prioritize Findings]
    D --> H
    H --> I[Generate Report]
```

This is where the workflow begins moving beyond a predefined sequence.

The next action can depend on the evidence returned by previous operations.

However, the architecture should include limits on retries, tool calls, execution time and resource consumption.

An agent that continuously repeats an unsuccessful operation is not necessarily intelligent. It may simply be consuming resources without making progress.

## 9. Adding Retrieval-Augmented Generation

The next step is connecting the audit workflow to a knowledge base.

Technical SEO recommendations often depend on official documentation, website-specific requirements, previous audit findings and implementation standards.

A RAG component could retrieve relevant information from:

- Google Search Central documentation
- Internal SEO guidelines
- Historical audit reports
- Website architecture documentation
- Structured data specifications
- Development team implementation notes

For example, when the audit discovers a canonical configuration issue, the agent could retrieve the relevant technical guidelines before generating its recommendation.

This creates a more useful workflow:

Website Audit → Issue Detection → Knowledge Retrieval → Evidence Evaluation → Recommendation

A retrieval system can use PostgreSQL with pgvector, Qdrant, FAISS or another appropriate search mechanism.

You do not necessarily need a vector database for a small project. Keyword-based retrieval or structured document search may be sufficient.

The distinction between conventional RAG and Agentic RAG is that the latter can dynamically decide what information to retrieve, which sources to consult and whether additional evidence is required.

Adding a document search tool does not automatically turn every workflow into Agentic RAG.

The decision-making and retrieval evaluation mechanisms still need to be designed.

## 10. Extending the Architecture with Additional Tools

One advantage of this approach is that you can expand it gradually.

For a technical SEO application, I would consider adding the following integrations.

### Claude Code + Playwright

Browser rendering checks, JavaScript-generated content inspection, screenshot capture and automated website testing.

### Claude Code + Google Search Console

Authorized access to search performance, indexing insights and supported inspection data.

### Claude Code + PostgreSQL

Historical audit storage, website records, issue tracking and performance comparisons.

### Claude Code + GitHub

Code review, repository analysis, issue management and implementation tracking.

### Claude Code + Docker

Repeatable development environments, dependency management and deployment consistency.

### Claude Code + Vector Search

Retrieval of technical documentation, internal knowledge and historical audit findings.

### Claude Code + Custom Python Tools

Website crawling, structured data extraction, competitor research and reporting.

Not every integration requires MCP. Some tasks can be performed more efficiently through existing command-line tools, direct APIs or conventional Python scripts.

MCP is especially useful when a capability needs to be discoverable and reusable across compatible AI applications.

## 11. Do You Really Need n8n or an Agent Framework?

This is a question worth considering before building a complicated AI automation system.

For the example in this article, the answer is no.

Claude Code, MCP and Python are sufficient to demonstrate a useful interactive tool-based workflow.

If you need scheduled website audits, you can introduce Python scheduling, cron or a background worker.

If you need to store results, SQLite or PostgreSQL may be enough.

If you need complex state management, conditional execution, resumable workflows or multi-agent coordination, a framework such as LangGraph may become useful.

Similarly, n8n can simplify integrations and recurring business workflows, particularly when non-developers need to maintain them.

My preferred development approach is to start with the smallest architecture that solves the actual problem.

Introduce additional frameworks only when their benefits justify the operational complexity.

For a standalone SaaS product, you would also need to evaluate the appropriate agent runtime, API access, authentication, deployment architecture and commercial usage terms. An interactive Claude Code session should not automatically be treated as a production multi-user backend.

## 12. Security and Reliability Considerations

Giving an AI application access to external tools introduces responsibilities that are easy to overlook during development.

An MCP server is not automatically safe simply because it uses a standardized protocol.

For production systems, consider implementing:

- Authentication and authorization.
- Explicit tool permissions.
- Input validation and network restrictions.
- Protection against server-side request forgery.
- Response size limits and request timeouts.
- API usage quotas.
- Execution logging.
- Secret management.
- Human approval for destructive operations.
- Protection against prompt injection in retrieved content.

For example, a website might contain text instructing an AI agent to ignore its original objective and execute another operation.

That text should be treated as untrusted website content, not as an authorized system instruction.

Similarly, a tool capable of modifying a production website should have stricter permissions than a tool that only reads metadata.

Start with read-only tools. Introduce write permissions and autonomous execution gradually, with clear approval boundaries.

## 13. A Possible Production Architecture

If I were expanding this demonstration into a complete SEO intelligence platform, I would organize it into several layers.

**Interface layer:** A Next.js dashboard for managing projects, running audits and reviewing results.

**Agent layer:** An appropriate LLM-powered runtime responsible for planning, tool selection and recommendation generation.

**Tool layer:** Python functions and MCP servers for reusable auditing capabilities.

**Data layer:** PostgreSQL for project records, audit history and issue management.

**Retrieval layer:** A searchable knowledge base for documentation and previous findings.

**Execution layer:** Background workers for crawling, scheduled checks and long-running tasks.

**Governance layer:** Permissions, approval workflows, logging, resource limits and monitoring.

The architecture could eventually support multiple specialized agents, including a technical SEO agent, an entity analysis agent, a content research agent and an AI search visibility agent.

However, I would validate each individual tool and workflow before introducing a hierarchical multi-agent system.

Reliable tools are the foundation of reliable agents.

## Final Thoughts

Claude Code becomes more interesting when we stop looking at it exclusively as a coding assistant.

Combined with MCP and Python, it can interact with custom tools, retrieve information and coordinate workflows around specific objectives.

For developers, this creates an opportunity to turn existing scripts into reusable AI-accessible capabilities.

For SEO professionals, it provides an approach to building intelligent audit systems that combine actual website data with contextual reasoning.

And for businesses, it offers a way to connect AI capabilities with existing operational tools without rebuilding every system from scratch.

The most useful AI applications are not necessarily the ones with the largest number of agents or the most complicated architecture.

Sometimes a few reliable Python functions, a well-defined objective and an appropriate tool interface are enough to build something genuinely useful.

That's the direction I'm interested in exploring further.

## References and Resources

- [Model Context Protocol Documentation](https://modelcontextprotocol.io/)
- [MCP Python SDK](https://github.com/modelcontextprotocol/python-sdk)
- [Claude Code MCP Documentation](https://code.claude.com/docs/en/mcp)
- [LangGraph](https://github.com/langchain-ai/langgraph)
- [Playwright for Python](https://playwright.dev/python/)
- [Google Search Central](https://developers.google.com/search)

## About the Author

**Piyush Kumar Soni | SEO, AI Search, LLMs & Automation**

My professional journey started in digital marketing in 2011 and gradually expanded into Technical SEO, web development, AI Search, Entity SEO, Retrieval-Augmented Generation and AI-powered automation.

I'm currently exploring how AI agents, MCP and information retrieval can improve search intelligence, website analysis and digital marketing workflows.

Explore my projects:

- [GitHub Profile](https://github.com/piyushsoni-ai)
- [SEO Master Skill](https://github.com/piyushsoni-ai/seo-master-skill)
- [Google Maps Scraper](https://github.com/piyushsoni-ai/google-maps-scraper)
- [GBP Audit + AI Visibility Extension](https://addons.mozilla.org/en-US/firefox/addon/gbp-audit-ai-visibility/)
- [LinkedIn](https://www.linkedin.com/in/piyushkumarsoni/)
- [Substack](https://piyushkumarsoni.substack.com/)

If you're experimenting with Claude Code, MCP or AI agents, I'd be interested to hear what you're building.

Are you using an agent orchestration framework, or do you prefer building lightweight workflows with Python and MCP?
