Skip to main content

mycode-sdk

Lightweight Python SDK for building AI agents. Multi-turn conversations, tool calling, session persistence, and streaming events. Provider adapters for Anthropic, OpenAI, Google, and more.

Install

uv add mycode-sdk
# or
pip install mycode-sdk

Quick start

import asyncio
from pathlib import Path

from mycode import Agent, tool


@tool
def read_file(path: str) -> str:
    """Read a UTF-8 text file.

    Args:
        path: File path, relative to the working directory.
    """

    return Path(path).read_text(encoding="utf-8")


async def main() -> None:
    agent = Agent(
        model="claude-sonnet-5",
        api_key="YOUR_API_KEY",
        tools=[read_file],
    )

    async for event in agent.achat("Read pyproject.toml and tell me the project name."):
        if event.type == "text":
            print(event.delta, end="", flush=True)


asyncio.run(main())

Agent(...) infers the provider from the model id. No tools are registered unless you pass tools=[...].

For a synchronous call, use run():

result = agent.run("Read pyproject.toml and tell me the project name.")
print(result.text)

Providers

The SDK infers the provider from the model string (claude-* to Anthropic, gpt-* to OpenAI, etc.). API keys are auto-discovered from environment variables:

Provider id Env var
Anthropic anthropic ANTHROPIC_API_KEY
OpenAI openai OPENAI_API_KEY
Google Gemini google GEMINI_API_KEY
Moonshot moonshotai MOONSHOT_API_KEY
MiniMax minimax MINIMAX_API_KEY
DeepSeek deepseek DEEPSEEK_API_KEY
Z.AI zai ZAI_API_KEY
OpenRouter openrouter OPENROUTER_API_KEY
Alibaba Cloud alibaba DASHSCOPE_API_KEY
xAI xai XAI_API_KEY
OpenAI-compatible openai_chat -

Pass api_key= to override the env var, api_base= for a custom endpoint. Model metadata is bundled from models.dev; pass context_window, supports_image_input, or supports_pdf_input to override.

Call agent.set_model(...) between turns to switch models; the conversation carries over.

Multi-turn conversations

Call achat() or run() again on the same Agent to continue:

agent = Agent(model="claude-sonnet-5", api_key="...")

agent.run("What is 2 + 2?")
agent.run("Now multiply that by 10.")  # remembers the earlier answer

agent.clear() drops in-memory history. agent.messages accumulates across calls.

Attachments

Pass attachments to achat() or run() to add files alongside the prompt:

from mycode import Attachment

agent.run("Describe these.", attachments=["diagram.png", "report.pdf", "notes.txt"])

# Or build them explicitly:
agent.run(
    "Review.",
    attachments=[
        Attachment.path("diagram.png"),
        Attachment.bytes(png_data, media_type="image/png"),
        Attachment.text("TODO: ship it", name="note.md"),
    ],
)

Images support image/png, image/jpeg, image/gif, image/webp; documents support application/pdf. Sending an image or PDF to a model without that capability yields an error event. A bad path or unsupported type raises ValueError before the provider is called.

Saving sessions

Pass session_dir to persist the conversation to disk. Each session lives in a subdirectory named by session_id:

from pathlib import Path

agent = Agent(
    model="claude-sonnet-5",
    api_key="...",
    session_dir=Path("./chats"),
    session_id="my-chat",
)

Construct another Agent with the same (session_dir, session_id) to load the conversation history.

Tools

Decorate a typed function with @tool:

from mycode import Agent, tool


@tool
def greet(name: str) -> str:
    """Return a friendly greeting.

    Args:
        name: Person name.
    """

    return f"hello, {name}"


agent = Agent(
    model="claude-sonnet-5",
    api_key="...",
    tools=[greet],
)

To call another registered tool from inside a tool, type the first parameter as ToolContext and dispatch by name:

from mycode import ToolContext, tool


@tool
def greet_team(ctx: ToolContext, names: list[str]) -> str:
    """Greet several people at once."""

    return "\n".join(ctx.call("greet", {"name": name}).output for name in names)

Async tools use await ctx.acall(name, args) instead.

Tool hooks

Inspect or replace tool calls before they run. Return None from before_tool to let the tool execute, or a ToolExecutionResult to skip it:

import os

from mycode import Agent, Hooks, ToolExecutionResult, tool

hooks = Hooks()


@tool
def delete_file(path: str) -> str:
    """Delete a file.

    Args:
        path: Path of the file to delete.
    """

    os.remove(path)
    return f"deleted {path}"


@hooks.before_tool
async def protect_dotfiles(ctx):
    if ctx.tool_name == "delete_file" and str(ctx.tool_input.get("path") or "").startswith("."):
        return ToolExecutionResult(output="error: blocked", is_error=True)
    return None


agent = Agent(
    model="claude-sonnet-5",
    api_key="...",
    tools=[delete_file],
    hooks=hooks,
)

@hooks.after_tool runs after the tool and can replace the result (audit, redact, etc.).

Further reading

See docs/sdk.md for the streaming event API, cancellation, retries, compaction, session internals, and the full Agent / @tool reference.

Metadata

Release files for mycode-sdk 0.21.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for mycode-sdk 0.21.0
File Size Uploaded
mycode_sdk-0.21.0.tar.gz 59.1 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for mycode-sdk 0.21.0
File Interpreter ABI Platform
mycode_sdk-0.21.0-py3-none-any.whl Python 3 none any Details

Total release size: 128.5 kB

Release files / mycode_sdk-0.21.0.tar.gz

Download URL mycode_sdk-0.21.0.tar.gz
Size 59.1 kB
Tags Source
SHA-256 checksum
How to use checksums
2ab764e72809df639a92a2c8de2585e2ec778cac88151d2429899dbc0cf5ba44
BLAKE2b-256 checksum
How to use checksums
c52749808935d2ccb2c6700f184377de781e8bc33cf4f84c0f603687844bb45a
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.13.1 {"installer":{"name":"uv","version":"0.13.1","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Release files / mycode_sdk-0.21.0-py3-none-any.whl

Download URL mycode_sdk-0.21.0-py3-none-any.whl
Size 69.5 kB
Tags Python 3
SHA-256 checksum
How to use checksums
e63ef4987e292f7c5b05b62ffaae8f89865f136df9babd17aaca2e3072701f1b
BLAKE2b-256 checksum
How to use checksums
0b0ca357d83353ef7d230d64935211a0dc03cac7170756ca55befa3dcb738088
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.13.1 {"installer":{"name":"uv","version":"0.13.1","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Release history Release notifications | RSS feed

This release

0.21.0 This release

2 release files

0.20.0

2 release files

0.19.0

2 release files

0.18.0

2 release files

0.17.0

2 release files

0.16.2

2 release files

0.16.1

2 release files

0.16.0

2 release files

0.14.0

2 release files

0.13.3

2 release files

0.13.2

2 release files

0.13.1

2 release files

0.13.0

2 release files

0.11.1

2 release files

0.11.0

2 release files

0.10.0

2 release files

0.9.5

2 release files

0.9.4

2 release files

0.9.3

2 release files

0.9.2

2 release files

0.9.1

2 release files

0.9.0

2 release files

0.8.10

2 release files

0.8.9

2 release files

0.8.8

2 release files

0.8.7

2 release files

0.8.6

2 release files

0.8.5

2 release files

0.8.4

2 release files

0.8.3

2 release files

0.8.2

2 release files

0.8.1

2 release files

0.8.0

2 release files

0.7.6

2 release files

0.7.5

2 release files

0.7.4

2 release files

0.7.3

2 release files

0.7.2

2 release files

0.7.1

2 release files

0.7.0

2 release files

0.6.0

2 release files

0.5.8

2 release files

0.5.7

2 release files

0.5.6

2 release files

0.5.5

2 release files

0.5.4

2 release files

0.5.3

2 release files

0.5.2

2 release files

0.5.1

2 release files

0.5.0

2 release files

0.4.3

2 release files

0.4.2

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page