Open in VS Code: From your cloned s26-06643 repository, run in the terminal:

code sse/11-advanced-mcp/11-advanced-mcp.ipynb

View source on GitHub

Module 11: Configuring & Extending AI Agents#

Teaching AI about your project, building custom skills, and extending capabilities.

Learning Objectives#

  1. Configure AI agents for your project with CLAUDE.md

  2. Create custom slash commands for repetitive tasks

  3. Build reusable skills as markdown prompt templates

  4. Understand the Model Context Protocol (MCP)

  5. Create simple MCP servers with custom tools

  6. Build command-line interfaces for your packages

The Configuration Spectrum#

AI agents can be customized at multiple levels, from simple text files to full server implementations:

Level

Mechanism

Effort

Capability

Project instructions

CLAUDE.md

Minutes

Tell AI about your project conventions

Custom commands

.claude/commands/*.md

Minutes

Reusable prompts for common tasks

Skills

Markdown templates

Hours

Domain-specific AI behaviors

MCP servers

Python server code

Hours-Days

Give AI new tools and data access

Start simple. Most projects only need the first two levels.

CLAUDE.md: Project Instructions#

A CLAUDE.md file in your project root tells the AI agent about your project. It’s read automatically whenever the agent starts in that directory.

What to Put in CLAUDE.md#

# Project: ScholarTools

## Overview
A Python package for querying the OpenAlex API for scholarly metadata.

## Conventions
- Use Google-style docstrings
- All functions must have type hints
- Tests go in tests/ directory using pytest
- Format with black, lint with ruff

## Architecture
- src/scholartools/api.py - API client functions
- src/scholartools/metrics.py - Citation metrics (h-index, etc.)
- tests/ - pytest test files mirroring src structure

## Important Notes
- Never hardcode API keys; use environment variables
- All API calls must include error handling and retries
- Keep functions small and focused

Where CLAUDE.md Files Live#

Location

Scope

~/CLAUDE.md

All projects (personal preferences)

~/.claude/CLAUDE.md

All projects (tool preferences)

./CLAUDE.md

This project only

./src/CLAUDE.md

This subdirectory

They stack: global settings apply everywhere, project settings add on top.

What Makes a Good CLAUDE.md#

  • Be specific: “Use Google-style docstrings” not “Write good docs”

  • Include examples: Show the pattern you want followed

  • Keep it current: Update as your project evolves

  • State constraints: “Never do X” is as useful as “Always do Y”

  • Document architecture: Help AI understand file organization

Context Engineering Reminder (from Module 00)

Before starting this exercise, think about what context the agent needs. For MCP/agent configuration, that means:

  • Before creating a CLAUDE.md, have the agent explore your project structure (ls, read key files) so it understands the codebase

  • Before building an MCP server, fetch the MCP specification or examples from the docs

  • When creating slash commands, show the agent examples of your common workflows so it can tailor the commands

Load the context first, then ask for the action.

Exercise 1: Create a CLAUDE.md (10 min)#

Create a CLAUDE.md file for your course project (or for the scholartools package from earlier assignments).

Include:

  1. A brief project overview

  2. Code conventions (docstring style, formatting, testing)

  3. File organization / architecture

  4. At least two constraints (“never” / “always” rules)

Test it:

  1. Start Claude Code in your project directory

  2. Ask it to create a new function

  3. Does it follow your conventions?

  4. Refine the CLAUDE.md based on what it gets wrong

Tip: Think of CLAUDE.md as onboarding documentation — if a new team member joined, what would they need to know?

Custom Slash Commands#

Slash commands are reusable prompts stored as markdown files. They save you from typing the same complex prompt repeatedly.

Creating a Command#

Commands live in .claude/commands/ in your project:

mkdir -p .claude/commands

Example: .claude/commands/add-tests.md

Write pytest tests for the file: $ARGUMENTS

Requirements:
- Use pytest fixtures for setup
- Include edge cases (empty input, None, invalid types)
- Use parametrize for multiple test cases
- Mock any external API calls
- Aim for >90% coverage of the target file
- Follow the existing test patterns in tests/

Usage:

> /add-tests src/scholartools/metrics.py

The $ARGUMENTS Variable#

The special $ARGUMENTS placeholder is replaced with whatever you type after the command name. This makes commands flexible:

  • /add-tests api.py replaces $ARGUMENTS with api.py

  • /review src/ replaces $ARGUMENTS with src/

More Command Examples#

.claude/commands/review.md — Code review:

Review the code in $ARGUMENTS for:
- Bugs and logic errors
- Missing error handling
- Security issues
- Performance problems
- Style consistency with CLAUDE.md conventions

For each issue found, explain the problem and suggest a fix.

.claude/commands/docstring.md — Add docstrings:

Add Google-style docstrings to all public functions and classes in $ARGUMENTS.

Each docstring should include:
- One-line summary
- Args section with types
- Returns section with type
- Raises section if applicable
- One usage example

Do not modify any code logic.

Exercise 2: Build Custom Commands (10 min)#

Create two custom slash commands for your project:

  1. A command you’d use often — Think about a task you do repeatedly. Some ideas:

    • /explain — Explain how a file or function works

    • /refactor — Refactor code following project conventions

    • /changelog — Generate a changelog entry from recent commits

    • /check — Run all quality checks and report issues

  2. A domain-specific command — Something specific to your project:

    • /add-endpoint — Add a new API endpoint with error handling

    • /add-metric — Add a new bibliometric function with tests

    • /lab-entry — Generate a lab notebook entry template

Test both commands and iterate on the prompt text until the output matches what you want.

Skills: Reusable Prompt Templates#

Skills are more detailed prompt templates that encode domain expertise. They’re like custom commands but longer and more structured, often including examples, constraints, and multi-step instructions.

Anatomy of a Skill#

A skill typically includes:

  1. When to use it (trigger conditions)

  2. Context (background knowledge the AI needs)

  3. Step-by-step instructions

  4. Examples of good output

  5. Constraints (what to avoid)

Example: A Scientific Data Analysis Skill#

# Scientific Data Analysis

Use this skill when analyzing experimental data.

## Steps
1. Load the data and print summary statistics
2. Check for missing values and outliers
3. Create appropriate visualizations
4. Fit a model if requested
5. Report results with uncertainty estimates

## Constraints
- Always report units
- Include error bars on all plots
- Use scipy.stats for statistical tests
- Report p-values and confidence intervals
- Never claim statistical significance without testing

## Example Output Format
Results:
- Mean: 4.52 +/- 0.13 (95% CI)
- R-squared: 0.94
- p-value: 0.003 (significant at alpha=0.05)

Skills vs. Commands#

Feature

Commands

Skills

Length

Short (5-20 lines)

Long (50+ lines)

Scope

Single task

Workflow or domain

Examples

Optional

Essential

Reusability

Within project

Across projects

What is MCP?#

The Model Context Protocol (MCP) is a standard for connecting AI models to external tools and data sources. It lets you give AI agents new capabilities beyond text generation.

MCP defines three types of extensions:

  • Tools: Functions the AI can call (e.g., search a database, run a calculation)

  • Resources: Data sources the AI can read (e.g., a database, file system)

  • Prompts: Pre-built prompt templates

Why Build MCP Servers?#

  • Domain expertise: Give AI access to your specialized tools and databases

  • Data access: Connect AI to private APIs, local databases, lab instruments

  • Automation: Let AI trigger real-world actions (run experiments, deploy code)

  • Safety: Control exactly what AI can and cannot do

Building a Simple MCP Server#

First, install the MCP SDK:

pip install mcp

Then create your server:

# openalex_mcp/server.py
from mcp.server import Server
import requests

server = Server("openalex")

@server.tool()
async def search_works(query: str, limit: int = 5) -> str:
    """Search OpenAlex for scholarly works.
    
    Args:
        query: Search query string
        limit: Maximum number of results to return
    """
    response = requests.get(
        "https://api.openalex.org/works",
        params={"search": query, "per_page": limit}
    )
    works = response.json()['results']
    
    result = []
    for w in works:
        result.append(f"- {w['title']} ({w['publication_year']})")
    
    return "\n".join(result)

@server.tool()
async def get_author_stats(name: str) -> str:
    """Get publication statistics for an author."""
    response = requests.get(
        "https://api.openalex.org/authors",
        params={"search": name}
    )
    authors = response.json()['results']
    
    if not authors:
        return f"Author '{name}' not found"
    
    a = authors[0]
    return (
        f"Author: {a['display_name']}\n"
        f"Works: {a['works_count']}\n"
        f"Citations: {a['cited_by_count']}"
    )

if __name__ == "__main__":
    server.run()

Configuring Claude Code to Use Your Server#

Add to .claude/settings.json in your project:

{
  "mcpServers": {
    "openalex": {
      "command": "python",
      "args": ["openalex_mcp/server.py"]
    }
  }
}

Now the AI can use your tools:

> Find papers about catalysis by John Kitchin

Claude: [Uses search_works and get_author_stats tools automatically]

Exercise 3: Build a Custom Tool (15 min)#

Choose one of these options:

Option A: MCP Server

Use AI to help you build a simple MCP server with 2 tools relevant to your project. For example:

  • A tool that searches your package’s data

  • A tool that runs one of your analysis functions

Configure it in .claude/settings.json and test it.

Option B: CLI with entry points

Add a command-line interface to your package using click or argparse:

# src/scholartools/cli.py
import click
from scholartools import search_works

@click.command()
@click.argument('query')
@click.option('--limit', default=5, help='Max results')
def main(query, limit):
    """Search for scholarly works."""
    results = search_works(query, limit=limit)
    for r in results:
        click.echo(f"  {r['title']} ({r['publication_year']})")

Add to pyproject.toml:

[project.scripts]
scholar = "scholartools.cli:main"

Then pip install -e . and test:

scholar "machine learning catalysis" --limit 3

Putting It All Together#

A well-configured project might look like:

my-project/
  CLAUDE.md                    # Project instructions
  .claude/
    commands/
      add-tests.md             # Custom command
      review.md                # Custom command
    settings.json              # MCP server config
  src/
    mypackage/
      __init__.py
      core.py
      cli.py                   # CLI entry point
  mcp_server/
    server.py                  # MCP tools
  tests/
  pyproject.toml

This gives you:

  • AI that understands your conventions (CLAUDE.md)

  • Reusable prompts for common tasks (commands)

  • AI that can use your domain tools (MCP)

  • A CLI for users who don’t use AI (cli.py)

Exercise 4: Configure Your Project (10 min)#

Set up the full configuration stack for your course project:

  1. Create or update your CLAUDE.md (if you haven’t already from Exercise 1)

  2. Create at least one custom slash command in .claude/commands/

  3. Test the workflow: start Claude Code, use your command, verify it follows CLAUDE.md conventions

Reflect:

  • How much time did the configuration save on a single task?

  • How much would it save over a week of development?

  • What other commands would be useful for your project?

The Future of AI-Assisted Development#

The tools in this course are evolving rapidly:

  • More capable agents: Longer context, better reasoning, fewer mistakes

  • Better integration: AI built into every stage of development

  • Domain specialization: AI trained for specific scientific fields

  • Human-AI teams: New collaboration patterns we haven’t invented yet

The skills you’ve learned — understanding fundamentals, directing AI effectively, evaluating output critically — will remain valuable regardless of how the tools change.

Summary#

Concept

Key Point

CLAUDE.md

Project instructions that AI reads automatically

Custom commands

Reusable prompts with $ARGUMENTS

Skills

Detailed domain-specific prompt templates

MCP

Standard protocol for giving AI new tools

CLIs

Make your package usable from the command line

Key Takeaways#

  • Start with CLAUDE.md — it’s the highest value for the lowest effort

  • Custom commands eliminate repetitive prompting

  • MCP lets you give AI genuinely new capabilities

  • A well-configured project makes AI dramatically more effective

Tips and Tricks#

  • Start with CLAUDE.md: Before building custom tools, write project instructions — it is the highest-value, lowest-effort configuration.

  • Prompt: “Generate a CLAUDE.md for a [type] project that uses [tools/frameworks]”: AI writes good project instructions when you describe the stack.

  • Keep slash commands short and reusable: A good command does one thing well — “run tests and report coverage” not “run tests, fix failures, update docs, and push.”

  • Prompt: “Create a slash command that [task]”: Describe what you want the command to do and the agent will write the markdown template.

  • Test MCP servers with simple tools first: Start with a tool that returns hardcoded data — once that works, add real logic.

  • Use skills for domain-specific patterns: If you repeatedly ask for the same kind of analysis, capture it as a skill instead of re-prompting each time.

  • Prompt: “What tools and context would make you more effective for this project?”: The agent often has useful suggestions about its own configuration.

  • Version-control your configuration: CLAUDE.md, slash commands, and skills should be committed to the repo so the whole team benefits.

Foundational Concepts to Commit to Memory#

  • CLAUDE.md = a plain text file in your project root that the AI agent reads automatically; it is the single highest-leverage configuration you can set up

  • Scope stacking = CLAUDE.md files at ~/, ~/.claude/, ./, and subdirectories all stack; global preferences apply everywhere, project-specific ones add on top

  • Custom commands = markdown files in .claude/commands/ that act as reusable prompt templates; $ARGUMENTS is replaced with whatever follows the command name

  • Skills vs. commands = commands are short, single-task prompts; skills are longer, domain-specific templates with examples, constraints, and multi-step instructions

  • MCP (Model Context Protocol) = a standard for giving AI agents new tools, data sources, and prompt templates beyond what they ship with

  • MCP server = a Python program that exposes tools via the MCP protocol; configured in .claude/settings.json so the AI can call your functions directly

  • CLI entry points = defined in pyproject.toml under [project.scripts]; they let users run your package from the command line without writing Python

  • Start simple = CLAUDE.md and custom commands cover most needs; only build MCP servers when you need the AI to call domain-specific functions

Knowing vs. Doing: Reflection#

This final module is about teaching AI to work the way you work — and that requires you to know how you work. Writing a good CLAUDE.md means you understand your own project’s conventions well enough to articulate them. Building a custom command means you have done a task enough times to know what the right prompt looks like. Creating an MCP server means you understand your domain well enough to decide what tools the AI needs. In every case, your knowledge is the input that makes the AI more capable. The AI amplifies what you know; it does not replace the knowing.

But here is the liberating part: you do not need to know everything before you start building. CLAUDE.md takes five minutes and immediately makes every AI interaction with your project better. You can write your first custom command after doing a task twice. You can build an MCP server in an afternoon with AI helping you write the boilerplate. The tools in this module are designed to reward incremental investment — a little configuration now saves hours later. The key is to start, not to start perfectly.

Throughout this course, the recurring theme has been the tension between learning and doing. You need to know enough to ask the right questions, evaluate the answers, and catch mistakes. But if you wait until you know everything, you will never build anything. AI agents have fundamentally shifted this balance. They let you operate beyond the boundaries of what you already know — reaching into unfamiliar territory, trying approaches you would not have thought of, and learning from the results. Your job is to bring judgment, context, and intent. The AI brings speed, breadth, and tireless execution. Together, you can build things that neither of you could build alone. That is the future of scientific software engineering, and you now have the tools to participate in it.

Additional Resources#