### Install Package from PyPI, Git URL, or Local Source: https://github.com/jmiao24/paper2agent/blob/main/agents/environment-python-manager.md Follow this priority order for installing packages: PyPI first, then Git URL, and finally local installation as a last resort. Activate your environment before running these commands. ```bash source -env/bin/activate # Try PyPI first (preferred) uv pip install # If PyPI fails, try git URL uv pip install git+https://github.com/user/repo.git@main # If both fail, clone locally (last resort) git clone https://github.com/user/repo.git uv pip install ./repo ``` -------------------------------- ### Install from requirements.txt Source: https://github.com/jmiao24/paper2agent/blob/main/agents/environment-python-manager.md Install dependencies listed in the requirements.txt file. Ensure your virtual environment is activated first. ```bash source -env/bin/activate uv pip install -r ./requirements.txt ``` -------------------------------- ### Install Additional Requirement Files Source: https://github.com/jmiao24/paper2agent/blob/main/agents/environment-python-manager.md Install dependencies from additional requirement files like requirements-dev.txt if they exist and are necessary. Activate your environment before installation. ```bash source -env/bin/activate uv pip install -r requirements-dev.txt # If exists and needed ``` -------------------------------- ### Generate Environment Summary Source: https://github.com/jmiao24/paper2agent/blob/main/agents/environment-python-manager.md Provides a template for summarizing the Python environment setup, including details like repository name, Python version, dependency count, and installation method. ```text Environment Setup Complete - Environment: -env - Python: - Dependencies: packages installed - Installation method: - Activation: source -env/bin/activate ``` ```text Non-PyPI installations: - : installed from (reason: ) ``` -------------------------------- ### Install Package from pyproject.toml Source: https://github.com/jmiao24/paper2agent/blob/main/agents/environment-python-manager.md When a pyproject.toml file exists, prioritize installing the package from PyPI. If that fails, attempt installation via a Git URL. Local installation is the final fallback. ```bash source -env/bin/activate uv pip install # Use project name from pyproject.toml ``` ```bash source -env/bin/activate uv pip install git+https://github.com/user/repo.git@main ``` ```bash source -env/bin/activate uv pip install -e . ``` -------------------------------- ### Install AlphaGenome Source: https://github.com/jmiao24/paper2agent/blob/main/templates/AlphaPOP/score_batch.ipynb Run this cell to install the AlphaGenome library. It ensures all necessary components are available for use. ```python # @title Install AlphaGenome # @markdown Run this cell to install AlphaGenome. from IPython.display import clear_output ! pip install alphagenome clear_output() ``` -------------------------------- ### Generate Requirements File Source: https://github.com/jmiao24/paper2agent/blob/main/agents/environment-python-manager.md Demonstrates how to generate a requirements.txt file from installed packages using `uv pip freeze`. This is crucial for reproducibility. ```bash uv pip freeze > requirements.txt ``` -------------------------------- ### Convert and Copy Tutorial File Source: https://github.com/jmiao24/paper2agent/blob/main/agents/tutorial-executor.md Converts Python (.py) or Markdown (.md) tutorial files to Jupyter notebooks and copies them for execution. Ensures the correct Python environment is activated and jupytext is installed. ```bash mkdir -p notebooks// source -env/bin/activate uv pip install jupytext jupytext --to notebook repo//.../. \ --output notebooks//_execution.ipynb ``` -------------------------------- ### Run Paper2Agent Basic Usage Source: https://github.com/jmiao24/paper2agent/blob/main/README.md Execute Paper2Agent to process all relevant tutorials from a research paper's codebase. Ensure you have completed the installation and setup. ```bash cd Paper2Agent bash Paper2Agent.sh \ --project_dir \ --github_url ``` -------------------------------- ### Tutorial Scanner Agent Output Source: https://context7.com/jmiao24/paper2agent/llms.txt Example JSON output from the tutorial-scanner agent, which discovers and classifies tutorials in a repository. It identifies runnable, parameterisable, and reusable code snippets for tool inclusion. ```jsonc // reports/tutorial-scanner-include-in-tools.json — example output { "scan_metadata": { "github_repo_name": "scanpy", "paper_name": "SCANPY: Large-Scale Single-Cell Gene Expression Data Analysis", "scan_date": "2025-01-15", "total_files_scanned": 24, "total_files_included_in_tools": 5, "success": true, "success_reason": "All candidate files evaluated; 5 qualify as tool-worthy tutorials" }, "tutorials": [ { "path": "docs/tutorials/basics/clustering.ipynb", "title": "Preprocessing and clustering", "description": "Demonstrates end-to-end scRNA-seq analysis on PBMC3k. Covers quality control, normalisation, HVG selection, PCA, neighbourhood graph, UMAP, and Leiden clustering. All steps are parameterised and produce reusable outputs.", "type": "notebook", "include_in_tools": true, "reason_for_include_or_exclude": "Contains complete, parameterisable analytical workflow with clearly defined inputs/outputs applicable to any AnnData dataset." } ] } ``` -------------------------------- ### Execute Tutorial Notebooks with Papermill Source: https://context7.com/jmiao24/paper2agent/llms.txt This sequence of commands outlines the internal process of the `tutorial-executor` agent. It includes copying the tutorial notebook, executing it using `papermill` within a virtual environment, installing necessary packages, and managing the final output files. ```bash mkdir -p notebooks/clustering/ cp repo/scanpy/docs/tutorials/basics/clustering.ipynb \ notebooks/clustering/clustering_execution.ipynb ``` ```bash source scanpy-env/bin/activate papermill notebooks/clustering/clustering_execution.ipynb \ notebooks/clustering/clustering_execution_v1.ipynb \ --kernel python3 ``` ```bash uv pip install leidenalg ``` ```bash cp notebooks/clustering/clustering_execution_v1.ipynb \ notebooks/clustering/clustering_execution_final.ipynb rm notebooks/clustering/clustering_execution_v1.ipynb \ notebooks/clustering/clustering_execution.ipynb ``` ```bash python tools/extract_notebook_images.py \ notebooks/clustering/clustering_execution_final.ipynb \ notebooks/clustering/images/ ``` -------------------------------- ### Install Missing Packages Source: https://github.com/jmiao24/paper2agent/blob/main/agents/tutorial-executor.md Resolve `ModuleNotFoundError` by installing the required package using `uv pip install`. This command should be run after activating the correct environment. ```bash source -env/bin/activate uv pip install ``` -------------------------------- ### Mount and Run MCP Server Source: https://context7.com/jmiao24/paper2agent/llms.txt Mounts a tool to an MCP server and runs it over HTTP. Ensure the FastMCP library is installed. ```python from fastmcp import FastMCP from tools.score_batch import score_batch_mcp mcp = FastMCP(name="AlphaPOP") mcp.mount(score_batch_mcp) if __name__ == "__main__": mcp.run(transport="http", host="127.0.0.1", port=8003) ``` -------------------------------- ### Setup and Imports Source: https://github.com/jmiao24/paper2agent/blob/main/templates/AlphaPOP/score_batch.ipynb This cell loads the AlphaGenome model and imports essential libraries for data manipulation and analysis. Ensure you have an API key for model creation. ```python # @title Setup and imports. from io import StringIO from alphagenome import colab_utils from alphagenome.data import genome from alphagenome.models import dna_client, variant_scorers from google.colab import data_table, files import pandas as pd from tqdm import tqdm data_table.enable_dataframe_formatter() # Load the model. dna_model = dna_client.create(colab_utils.get_api_key()) ``` -------------------------------- ### Install and Configure Claude Code Source: https://github.com/jmiao24/paper2agent/blob/main/README.md Install Claude Code globally using npm and then run the 'claude' command to configure it. This is a prerequisite for using Paper2Agent with Claude Code. ```bash npm install -g @anthropic-ai/claude-code claude ``` -------------------------------- ### Create Scanpy Agent for Preprocessing and Clustering Source: https://github.com/jmiao24/paper2agent/blob/main/README.md Example of creating an AI agent from the Scanpy research paper codebase, filtering for tutorials related to preprocessing and clustering. ```bash # Filter by tutorial title bash Paper2Agent.sh \ --project_dir Scanpy_Agent \ --github_url https://github.com/scverse/scanpy \ --tutorials "Preprocessing and clustering" # Filter by tutorial URL bash Paper2Agent.sh \ --project_dir Scanpy_Agent \ --github_url https://github.com/scverse/scanpy \ --tutorials "https://github.com/scverse/scanpy/blob/main/docs/tutorials/basics/clustering.ipynb" ``` -------------------------------- ### Install and Verify MCP Agent Source: https://context7.com/jmiao24/paper2agent/llms.txt Installs a generated MCP agent into Claude Code and verifies its registration. This command requires the path to the Python executable for the agent's environment. ```bash # Install the generated MCP into Claude Code after pipeline completion fastmcp install claude-code AlphaGenome_Agent/src/alphagenome_mcp.py \ --python AlphaGenome_Agent/alphagenome-env/bin/python # Verify the server is registered claude mcp list # Expected: alphagenome stdio ... ``` -------------------------------- ### Set Up Isolated Python Environments with uv Source: https://context7.com/jmiao24/paper2agent/llms.txt These bash commands demonstrate setting up isolated Python environments using 'uv'. They cover creating a virtual environment, installing dependencies from PyPI or Git, and verifying package imports. A 'conftest.py' is generated to configure pytest for the project. ```bash # Commands the agent issues internally (shown for reference): # 1. Create isolated env (Python ≥ 3.10) uv venv --python 3.11 scanpy-env # 2. Install base tooling source scanpy-env/bin/activate uv pip install fastmcp pytest pytest-asyncio papermill nbclient ipykernel imagehash # 3. Install project from PyPI (preferred) uv pip install scanpy # 4. Fallback: install from git if PyPI version is insufficient uv pip install git+https://github.com/scverse/scanpy.git@main # 5. Verify imports python -c "import scanpy; print(scanpy.__version__)" # 6. Generated conftest.py (written to project root) cat > conftest.py << 'EOF' import sys, pytest from pathlib import Path import matplotlib, matplotlib.pyplot as plt def pytest_configure(config): project_root = Path(__file__).parent.resolve() if str(project_root) not in sys.path: sys.path.insert(0, str(project_root)) @pytest.fixture(autouse=True) def no_plot_show(monkeypatch): matplotlib.use("Agg") monkeypatch.setattr(plt, "show", lambda: None) EOF ``` -------------------------------- ### Install Missing Package Source: https://github.com/jmiao24/paper2agent/blob/main/agents/test-verifier-improver.md This command installs a missing Python package using uv pip. Replace `` with the actual package name. ```bash uv pip install ``` -------------------------------- ### Example Query for AlphaGenome Agent Source: https://github.com/jmiao24/paper2agent/blob/main/README.md This is an example of a query you can input to the AlphaGenome Agent for genomics data interpretation. ```text Analyze heart gene expression data with AlphaGenome MCP to identify the causal gene for the variant chr11:116837649:T>G, associated with Hypoalphalipoproteinemia. ``` -------------------------------- ### Install Python Dependencies Source: https://github.com/jmiao24/paper2agent/blob/main/README.md Install the necessary Python dependencies for Paper2Agent using pip. Ensure you are in the cloned Paper2Agent directory. ```bash pip install fastmcp ``` -------------------------------- ### Clone Paper2Agent Repository Source: https://github.com/jmiao24/paper2agent/blob/main/README.md Clone the Paper2Agent repository to your local machine. This is the first step in the installation process. ```bash git clone https://github.com/jmiao24/Paper2Agent.git cd Paper2Agent ``` -------------------------------- ### Create Python Virtual Environment with uv Source: https://github.com/jmiao24/paper2agent/blob/main/agents/environment-python-manager.md Use this command to create a virtual environment with a specific Python version and install base dependencies. Ensure the selected Python version is 3.10 or higher. ```bash uv venv --python -env source -env/bin/activate uv pip install fastmcp pytest pytest-asyncio papermill nbclient ipykernel imagehash ``` -------------------------------- ### Fetch Data using Pooch Source: https://github.com/jmiao24/paper2agent/blob/main/agents/benchmark-extractor.md Fetch specific data files (e.g., H5 matrices) using the initialized Pooch data fetcher. Ensure all necessary setup steps, including registry loading, are completed beforehand. ```python EXAMPLE_DATA.fetch('s1d1_filtered_feature_bc_matrix.h5') ``` ```python EXAMPLE_DATA.fetch('s1d3_filtered_feature_bc_matrix.h5') ``` -------------------------------- ### Create TISSUE Agent Source: https://github.com/jmiao24/paper2agent/blob/main/README.md Example of creating an AI agent from the TISSUE research paper codebase for uncertainty-calibrated single-cell spatial transcriptomics analysis. ```bash bash Paper2Agent.sh \ --project_dir TISSUE_Agent \ --github_url https://github.com/sunericd/TISSUE ``` -------------------------------- ### Executed Notebooks Report Structure Source: https://context7.com/jmiao24/paper2agent/llms.txt Example JSON output from `reports/executed_notebooks.json`, detailing the execution path and source URL of a processed tutorial notebook. ```json // reports/executed_notebooks.json — example output { "clustering": { "execution_path": "notebooks/clustering/clustering_execution_final.ipynb", "http_url": "https://github.com/scverse/scanpy/blob/main/docs/tutorials/basics/clustering.ipynb" } } ``` -------------------------------- ### Manual Launch with Local MCP Server Source: https://github.com/jmiao24/paper2agent/blob/main/README.md Restart your AI agent manually by installing Claude Code with a local MCP server. This command should be run from the working directory. ```bash cd fastmcp install claude-code /src/_mcp.py \ --python /-env/bin/python ``` -------------------------------- ### Activate Virtual Environment Source: https://github.com/jmiao24/paper2agent/blob/main/agents/test-verifier-improver.md This command activates a Python virtual environment. Ensure the environment name matches your project's setup. ```bash source -env/bin/activate ``` -------------------------------- ### Python MCP Server Tool Implementation Template Source: https://github.com/jmiao24/paper2agent/blob/main/agents/tutorial-tool-extractor-implementor.md Use this template to create new tools for the MCP Server. It includes standard imports, project structure setup, input/output directory configuration, and a basic tool function structure with parameter annotations and validation. ```python """ . This MCP Server provides tools: 1. : 2. : ... All tools extracted from `/.../.`. """ # Standard imports from typing import Annotated, Literal, Any import pandas as pd import numpy as np from pathlib import Path import os from fastmcp import FastMCP from datetime import datetime # Project structure PROJECT_ROOT = Path(__file__).parent.parent.parent.resolve() DEFAULT_INPUT_DIR = PROJECT_ROOT / "tmp" / "inputs" DEFAULT_OUTPUT_DIR = PROJECT_ROOT /"tmp" / "outputs" INPUT_DIR = Path(os.environ.get("_INPUT_DIR", DEFAULT_INPUT_DIR)) OUTPUT_DIR = Path(os.environ.get("_OUTPUT_DIR", DEFAULT_OUTPUT_DIR)) # Ensure directories exist INPUT_DIR.mkdir(parents=True, exist_ok=True) OUTPUT_DIR.mkdir(parents=True, exist_ok=True) # Timestamp for unique outputs timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") # MCP server instance _mcp = FastMCP(name="") @_mcp.tool def ( # Primary data inputs data_path: Annotated[str | None, "Path to input data file with extension <.ext>. The header of the file should include the following columns: , , "] = None, # Analysis parameters with tutorial default param1: Annotated[float, "Analysis parameter 1"] = 0.05, param2: Annotated[Literal["method1", "method2"], "Analysis method"] = "method1", out_prefix: Annotated[str | None, "Output file prefix"] = None, ) -> dict: """ . Input is and output is . """ # Input file validation only if data_path is None: raise ValueError("Path to input data file must be provided") # File existence validation data_file = Path(data_path) if not data_file.exists(): raise FileNotFoundError(f"Input file not found: {data_path}") # Load data data = pd.read_csv(data_path) # Tool implementation here... # Return standardized format return { "message": "Analysis completed successfully", "reference": "https://github.com//blob/main/.../.", "artifacts": [ { "description": "Analysis results", "path": str(output_file.resolve()) } ] } ``` -------------------------------- ### Create AlphaGenome Agent Source: https://github.com/jmiao24/paper2agent/blob/main/README.md Example of creating an AI agent from the AlphaGenome research paper codebase for genomic data interpretation, requiring an API key. ```bash bash Paper2Agent.sh \ --project_dir AlphaGenome_Agent \ --github_url https://github.com/google-deepmind/alphagenome \ --api ``` -------------------------------- ### launch_remote_mcp.sh — Connect to a hosted Paper MCP server Source: https://context7.com/jmiao24/paper2agent/llms.txt Registers a remotely hosted MCP server (e.g., on Hugging Face Spaces) with Claude Code and launches an interactive session, writing a `CLAUDE.md` workflow guide into the working directory. ```APIDOC ## launch_remote_mcp.sh — Connect to a hosted Paper MCP server ### Description Registers a remotely hosted MCP server (e.g., on Hugging Face Spaces) with Claude Code and launches an interactive session, writing a `CLAUDE.md` workflow guide into the working directory. ### Usage Examples Connect to the public AlphaGenome Paper Agent: ```bash bash launch_remote_mcp.sh \ --working_dir analysis_dir \ --mcp_name alphagenome \ --mcp_url https://Paper2Agent-alphagenome-mcp.hf.space ``` Upload a local data file to the remote MCP server for analysis: ```bash curl -F "file=@/absolute/path/to/variants.vcf" \ https://Paper2Agent-alphagenome-mcp.hf.space/upload ``` Download a result file produced by the remote MCP server: ```bash wget https://Paper2Agent-alphagenome-mcp.hf.space/outputs/score_batch_variants_20250101_120000.csv ``` Re-open an existing agent session (no re-registration needed): ```bash cd analysis_dir claude ``` ### Parameters - `--working_dir` (string) - Required - The directory for the analysis session. - `--mcp_name` (string) - Required - The name of the MCP server. - `--mcp_url` (string) - Required - The URL of the remote MCP server. ### Related Commands - `curl` for uploading files. - `wget` for downloading files. - `claude` for interacting with an existing agent session. ``` -------------------------------- ### Consolidated Reporting Template Source: https://github.com/jmiao24/paper2agent/blob/main/prompts/step1_prompt.md Use this template to generate a final summary combining results from both agents. It includes environment setup details, tutorial analysis, and execution metrics. ```text Environment Setup & Tutorial Discovery Complete Environment Status: - Environment: ${github_repo_name}-env - Python Version: [version] - Dependencies: [count] packages installed - Activation: source ${github_repo_name}-env/bin/activate Tutorial Analysis: - Total tutorials scanned: [count] - Tutorials included in tools: [count] - Filter applied: [filter_status] - Quality assessment: [pass/issues] Execution Metrics: - Environment setup time: [duration] - Tutorial scanning time: [duration] - Total execution time: [duration] ``` -------------------------------- ### Optional Parameter Annotation Source: https://github.com/jmiao24/paper2agent/blob/main/agents/tutorial-tool-extractor-implementor.md Illustrates annotating an optional boolean parameter with a meaningful default value taken from the tutorial, indicating whether to show transcription start sites. ```python show_tss: Annotated[bool, "Show transcription start sites"] = True, # From tutorial ``` -------------------------------- ### Pytest Global Configuration (conftest.py) Source: https://github.com/jmiao24/paper2agent/blob/main/agents/environment-python-manager.md Create this conftest.py file in the project root to configure pytest, ensuring proper module discovery and path setup for tests. It also disables plt.show() to prevent tests from blocking. ```python """ Global pytest configuration for project This ensures proper module discovery and path setup for all tests. """ import sys from pathlib import Path import matplotlib import matplotlib.pyplot as plt import pytest def pytest_configure(config): """Configure pytest to add the project root to sys.path.""" # Get the project root directory (where this conftest.py is located) project_root = Path(__file__).parent.resolve() # Add to sys.path if not already there if str(project_root) not in sys.path: sys.path.insert(0, str(project_root)) @pytest.fixture(autouse=True) def no_plot_show(monkeypatch): """Disable plt.show() during tests so figures don't block.""" matplotlib.use("Agg") # non-interactive backend monkeypatch.setattr(plt, "show", lambda: None) ``` -------------------------------- ### Copy Tutorial Notebook Source: https://github.com/jmiao24/paper2agent/blob/main/agents/tutorial-executor.md Copies a tutorial notebook to the execution directory. Use this when the source file is already in .ipynb format. ```bash mkdir -p notebooks// cp repo//.../.ipynb notebooks//_execution.ipynb ``` -------------------------------- ### Create and Validate Pytest Tests with Claude Code Agent Source: https://context7.com/jmiao24/paper2agent/llms.txt This Python script generates and runs pytest files for tool functions. It includes fixtures for server setup and test directories, and asserts the correctness of the tool's output and artifacts. Ensure the 'fastmcp' library is installed. ```python # tests/code/clustering/scanpy_quality_control_cells_test.py — generated example from __future__ import annotations import pathlib, pytest, sys, os from fastmcp import Client project_root = pathlib.Path(__file__).parent.parent.parent.parent sys.path.insert(0, str(project_root)) @pytest.fixture def server(test_directories): module_name = "src.tools.clustering" if module_name in sys.modules: del sys.modules[module_name] import src.tools.clustering return src.tools.clustering.clustering_mcp @pytest.fixture def test_directories(): input_dir = pathlib.Path(__file__).parent.parent.parent / "data" / "clustering" output_dir = pathlib.Path(__file__).parent.parent.parent / "results" / "clustering" input_dir.mkdir(parents=True, exist_ok=True) output_dir.mkdir(parents=True, exist_ok=True) old_out = os.environ.get("CLUSTERING_OUTPUT_DIR") os.environ["CLUSTERING_OUTPUT_DIR"] = str(output_dir.resolve()) yield {"input_dir": input_dir, "output_dir": output_dir} if old_out is not None: os.environ["CLUSTERING_OUTPUT_DIR"] = old_out else: os.environ.pop("CLUSTERING_OUTPUT_DIR", None) @pytest.fixture def scanpy_quality_control_cells_inputs(test_directories) -> dict: # Exact tutorial values from clustering_execution_final.ipynb return { "adata_path": str(test_directories["input_dir"] / "pbmc3k_raw.h5ad"), "min_genes": 200, "min_cells": 3, "max_pct_mito": 5.0, "out_prefix": "tutorial_qc", } @pytest.mark.asyncio async def test_scanpy_quality_control_cells(server, scanpy_quality_control_cells_inputs, test_directories): async with Client(server) as client: result = await client.call_tool("scanpy_quality_control_cells", scanpy_quality_control_cells_inputs) data = result.data assert data is not None assert "message" in data and "artifacts" in data # Tutorial output shows 2,638 cells after QC assert "2638" in data["message"], f"Expected 2638 cells, got: {data['message']}" # Verify output files exist artifacts = data["artifacts"] assert len(artifacts) == 2 for art in artifacts: assert pathlib.Path(art["path"]).exists(), f"Artifact missing: {art['path']}" # Validate CSV structure import pandas as pd df = pd.read_csv(artifacts[1]["path"]) assert "pct_counts_mt" in df.columns assert (df["pct_counts_mt"] <= 5.0).all() ``` -------------------------------- ### Execute Tutorial with Papermill Source: https://github.com/jmiao24/paper2agent/blob/main/agents/tutorial-executor.md Run the tutorial notebook using papermill for robust execution and progress tracking. Ensure your environment is activated before running. ```bash source -env/bin/activate papermill notebooks//_execution.ipynb \ notebooks//_execution_v1.ipynb \ --kernel python3 ``` -------------------------------- ### Import Required Packages for Agent Tutorial Source: https://github.com/jmiao24/paper2agent/blob/main/agents/tutorial-executor.md Ensure all necessary packages are imported at the beginning of the notebook. Add any other required packages as needed for the tutorial's functionality. ```python # Import required packages import os import sys import numpy as np import pandas as pd # Add other packages as needed ``` -------------------------------- ### Example Code Cell Source: https://github.com/jmiao24/paper2agent/blob/main/agents/tutorial-executor.md This is an example of a code cell that should be kept during the cleaning process. It represents executable code within a notebook. ```python Code cell (keep this): ``` -------------------------------- ### Execute Tutorial with Jupyter nbconvert Source: https://github.com/jmiao24/paper2agent/blob/main/agents/tutorial-executor.md An alternative method to execute tutorial notebooks using `jupyter nbconvert`. This method is not recommended due to less effective progress tracking compared to papermill. ```bash source -env/bin/activate uv pip install jupyter nbclient nbconvert jupyter nbconvert --to notebook --execute \ notebooks//_execution.ipynb \ --inplace \ --ExecutePreprocessor.timeout=600 ``` -------------------------------- ### Parallel Agent Launch using Task Tool Source: https://github.com/jmiao24/paper2agent/blob/main/prompts/step1_prompt.md Execute environment-python-manager and tutorial-scanner agents simultaneously using the Task tool with concurrent calls. Monitor progress with 10-minute timeouts and implement graceful failure handling. ```bash Task 1: environment-python-manager - Mission: Set up ${github_repo_name}-env with Python ≥3.10 - Working directory: Current directory (NOT repo/ subfolder) - Requirements: uv environment, pytest configuration, dependency installation - Output: reports/environment-manager_results.md Task 2: tutorial-scanner - Mission: Scan repo/${github_repo_name}/ for tool-worthy tutorials - Filter parameter: ${tutorial_filter} (if provided) - Requirements: Strict filtering, quality assessment, JSON output generation - Output: reports/tutorial-scanner.json + reports/tutorial-scanner-include-in-tools.json ``` -------------------------------- ### Paper2Agent.sh — Main pipeline entry point Source: https://context7.com/jmiao24/paper2agent/llms.txt Orchestrates the entire end-to-end pipeline: clones a GitHub repo, sets up a Python environment, discovers tutorials, executes them, extracts tools, builds an MCP server, and launches Claude Code. ```APIDOC ## Paper2Agent.sh — Main pipeline entry point ### Description Orchestrates the entire end-to-end pipeline: clones a GitHub repo, sets up a Python environment, discovers tutorials, executes them, extracts tools, builds an MCP server, and launches Claude Code. ### Usage Examples Minimal usage — process all tutorials in a repo: ```bash bash Paper2Agent.sh \ --project_dir TISSUE_Agent \ --github_url https://github.com/sunericd/TISSUE ``` Filter to a specific tutorial by title: ```bash bash Paper2Agent.sh \ --project_dir Scanpy_Agent \ --github_url https://github.com/scverse/scanpy \ --tutorials "Preprocessing and clustering" ``` Filter by tutorial file URL: ```bash bash Paper2Agent.sh \ --project_dir Scanpy_Agent \ --github_url https://github.com/scverse/scanpy \ --tutorials "https://github.com/scverse/scanpy/blob/main/docs/tutorials/basics/clustering.ipynb" ``` Repo requiring an API key + full benchmarking: ```bash bash Paper2Agent.sh \ --project_dir AlphaGenome_Agent \ --github_url https://github.com/google-deepmind/alphagenome \ --api YOUR_ALPHAGENOME_API_KEY \ --benchmark ``` Disable verbose progress output: ```bash VERBOSE=0 bash Paper2Agent.sh \ --project_dir MyAgent \ --github_url https://github.com/example/myrepo ``` ### Parameters - `--project_dir` (string) - Required - The directory to store the agent project. - `--github_url` (string) - Required - The URL of the GitHub repository. - `--tutorials` (string) - Optional - Filters tutorials by title or URL. - `--api` (string) - Optional - API key for services that require it. - `--benchmark` - Optional - Enables benchmarking mode. ``` -------------------------------- ### Initialize Pooch Data Fetcher Source: https://github.com/jmiao24/paper2agent/blob/main/agents/benchmark-extractor.md Create a Pooch data fetcher instance, specifying the cache path and base URL for data. Load the registry from a DOI to access registered datasets. ```python EXAMPLE_DATA = pooch.create(path=pooch.os_cache('scverse_tutorials'), base_url='doi:10.6084/m9.figshare.22716739.v1/') EXAMPLE_DATA.load_registry_from_doi() ``` -------------------------------- ### Run Paper2Agent Targeted Tutorial Processing Source: https://github.com/jmiao24/paper2agent/blob/main/README.md Process specific tutorials from a research paper's codebase by providing a tutorial URL or title. This allows for focused agent creation. ```bash bash Paper2Agent.sh \ --project_dir \ --github_url \ --tutorials ``` -------------------------------- ### Inject API Key into Notebooks Source: https://github.com/jmiao24/paper2agent/blob/main/prompts/step2_prompt.md When an API key is provided, this code demonstrates how to inject it into notebooks for services like OpenAI, Anthropic, and Google Generative AI. Ensure the necessary libraries are imported. ```python # API Configuration api_key = "${api_key}" openai.api_key = api_key # For OpenAI # client = anthropic.Anthropic(api_key=api_key) # For Anthropic # etc. ``` -------------------------------- ### Copy Final Execution Notebook Source: https://github.com/jmiao24/paper2agent/blob/main/agents/tutorial-executor.md Use this command to rename the final iteration of the execution notebook to the standard final version name. Replace `` and `` with the actual tutorial name and final version number. ```bash cp notebooks//_execution_v.ipynb notebooks//_execution_final.ipynb ``` -------------------------------- ### Load Scanpy PBMC3K Dataset Source: https://github.com/jmiao24/paper2agent/blob/main/agents/benchmark-extractor.md Load the PBMC3k dataset directly using Scanpy's dataset utility. No prior setup or initialization is required for this dataset. ```python sc.datasets.pbmc3k() ``` -------------------------------- ### Correct Numerical Assertions in Python Source: https://github.com/jmiao24/paper2agent/blob/main/agents/test-verifier-improver.md Illustrates correct assertion strategies using exact numbers from tutorial outputs and tutorial-reported statistics. Only assert values explicitly demonstrated in the tutorial. ```python # CORRECT: Using exact numbers from tutorial output assert len(filtered_cells) == 8732, f"Expected 8732 cells after QC (from tutorial), got {len(filtered_cells)}" ``` ```python # CORRECT: Using tutorial-reported ranges/statistics assert mitochondrial_ratio == pytest.approx(0.156, rel=0.1), "Tutorial shows ~15.6% mitochondrial content" ``` ```python # CORRECT: Only assert what tutorial explicitly demonstrates # If tutorial doesn't show cell counts, don't assert them ``` -------------------------------- ### Report Tutorial Execution Status Source: https://github.com/jmiao24/paper2agent/blob/main/agents/tutorial-executor.md A simple text format for reporting the status of a tutorial's execution, including its name, status (Success/Failed), and any relevant reason for failure. ```text Tutorial Execution Complete - Tutorial: - Status: Success/Failed - Reason: ``` -------------------------------- ### Preserving Exact Tutorial Structure for PCA Visualization Source: https://github.com/jmiao24/paper2agent/blob/main/agents/tutorial-tool-extractor-implementor.md When adapting tutorial code, preserve the exact structure, including lists for color and dimensions, rather than creating generalized patterns. This function visualizes PCA. ```python # Tutorial shows: # sc.pl.pca(adata, color=["sample", "sample", "pct_counts_mt", "pct_counts_mt"], # dimensions=[(0, 1), (2, 3), (0, 1), (2, 3)], ncols=2, size=2) # WRONG: Creating generalized patterns # color_vars: Annotated[str, "Comma-separated list"] = "sample,pct_counts_mt" # extended_colors = color_list * 2 # Creating artificial pattern # CORRECT: Preserve exact tutorial structure color_list: Annotated[list, "Color variables"] = ["sample", "sample", "pct_counts_mt", "pct_counts_mt"] dimensions_list: Annotated[list, "PC dimensions"] = [(0, 1), (2, 3), (0, 1), (2, 3)] sc.pl.pca(adata, color=color_list, dimensions=dimensions_list, ncols=2, size=2) ``` -------------------------------- ### Tutorial Executor Task Definition Source: https://github.com/jmiao24/paper2agent/blob/main/prompts/step2_prompt.md This outlines the task for the tutorial-executor agent, specifying its mission, inputs, environment, API key handling, requirements, and expected outputs for tutorial execution. ```text Task: tutorial-executor - Mission: Execute all tutorials from tutorial-scanner results - Input: reports/tutorial-scanner-include-in-tools.json - Environment: ${github_repo_name}-env - API Key: "${api_key}" (if provided, inject into notebooks requiring API access) - Requirements: Generate execution notebooks, handle errors, extract images - Output: notebooks/ directory structure + reports/executed_notebooks.json ``` -------------------------------- ### Generated Python Tool for Cell Clustering Source: https://context7.com/jmiao24/paper2agent/llms.txt A simplified example of a Python module generated by the `tutorial-tool-extractor-implementor` agent. This module defines tools for single-cell RNA-seq preprocessing and clustering using scanpy and the FastMCP framework. ```python # src/tools/clustering.py — generated output example (simplified) """ Single-cell RNA-seq preprocessing and clustering using scanpy. This MCP Server provides 5 tools: 1. scanpy_quality_control_cells: Filter cells by QC metrics 2. scanpy_normalize_log_transform: Normalise and log-transform counts 3. scanpy_select_highly_variable_genes: Select HVGs for downstream analysis 4. scanpy_cluster_cells: Compute PCA, neighbours, UMAP, and Leiden clustering 5. scanpy_annotate_cell_types: Assign cell-type labels via marker genes """ from typing import Annotated, Literal, Any import pandas as pd from pathlib import Path import os from fastmcp import FastMCP from datetime import datetime PROJECT_ROOT = Path(__file__).parent.parent.parent.resolve() DEFAULT_OUTPUT_DIR = PROJECT_ROOT / "tmp" / "outputs" OUTPUT_DIR = Path(os.environ.get("CLUSTERING_OUTPUT_DIR", DEFAULT_OUTPUT_DIR)) OUTPUT_DIR.mkdir(parents=True, exist_ok=True) timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") clustering_mcp = FastMCP(name="clustering") @clustering_mcp.tool def scanpy_quality_control_cells( adata_path: Annotated[str | None, "Path to AnnData .h5ad file"] = None, min_genes: Annotated[int, "Minimum genes per cell"] = 200, min_cells: Annotated[int, "Minimum cells per gene"] = 3, max_pct_mito: Annotated[float, "Maximum % mitochondrial reads"] = 5.0, out_prefix: Annotated[str | None, "Output file prefix"] = None, ) -> dict: """ Filter low-quality cells and genes from scRNA-seq data using scanpy QC metrics. Input is an AnnData .h5ad file and output is a filtered AnnData file and QC summary CSV. """ import scanpy as sc if adata_path is None: raise ValueError("Path to AnnData file must be provided") p = Path(adata_path) if not p.exists(): raise FileNotFoundError(f"Input file not found: {adata_path}") adata = sc.read_h5ad(adata_path) sc.pp.filter_cells(adata, min_genes=min_genes) sc.pp.filter_genes(adata, min_cells=min_cells) adata.var["mt"] = adata.var_names.str.startswith("MT-") sc.pp.calculate_qc_metrics(adata, qc_vars=["mt"], percent_top=None, log1p=False, inplace=True) adata = adata[adata.obs.pct_counts_mt < max_pct_mito] prefix = out_prefix or f"qc_{timestamp}" out_h5ad = OUTPUT_DIR / f"{prefix}.h5ad" out_csv = OUTPUT_DIR / f"{prefix}_summary.csv" adata.write_h5ad(str(out_h5ad)) adata.obs[["n_genes_by_counts", "total_counts", "pct_counts_mt"]].to_csv(str(out_csv)) return { "message": f"QC complete: {adata.n_obs} cells × {adata.n_vars} genes retained", "reference": "https://github.com/scverse/scanpy/blob/main/docs/tutorials/basics/clustering.ipynb", "artifacts": [ {"description": "Filtered AnnData object", "path": str(out_h5ad.resolve())}, {"description": "QC metrics summary", "path": str(out_csv.resolve())} ] } ``` -------------------------------- ### Verify Agent Loading Source: https://github.com/jmiao24/paper2agent/blob/main/README.md Use 'claude mcp list' or '\mcp' within Claude Code to verify that your repository-specific MCP server is loaded. ```bash claude mcp list ``` -------------------------------- ### Run Paper2Agent Pipeline Source: https://context7.com/jmiao24/paper2agent/llms.txt Use this script to orchestrate the end-to-end pipeline. It clones a GitHub repo, sets up a Python environment, discovers tutorials, executes them, extracts tools, builds an MCP server, and launches Claude Code. Supports filtering by tutorial title or URL, API keys, and benchmarking. ```bash bash Paper2Agent.sh \ --project_dir TISSUE_Agent \ --github_url https://github.com/sunericd/TISSUE ``` ```bash bash Paper2Agent.sh \ --project_dir Scanpy_Agent \ --github_url https://github.com/scverse/scanpy \ --tutorials "Preprocessing and clustering" ``` ```bash bash Paper2Agent.sh \ --project_dir Scanpy_Agent \ --github_url https://github.com/scverse/scanpy \ --tutorials "https://github.com/scverse/scanpy/blob/main/docs/tutorials/basics/clustering.ipynb" ``` ```bash bash Paper2Agent.sh \ --project_dir AlphaGenome_Agent \ --github_url https://github.com/google-deepmind/alphagenome \ --api YOUR_ALPHAGENOME_API_KEY \ --benchmark ``` ```bash VERBOSE=0 bash Paper2Agent.sh \ --project_dir MyAgent \ --github_url https://github.com/example/myrepo ```