OpenSpace で自己進化型 AI エージェントを構築
OpenSpace は、MCP やスキル進化機能を活用し、低コストで再利用可能な自己進化する AI エージェントを構築・管理するワークフローとツールを提供します。
AIニュース価値スコアβ
技術分析AI関連度、新規性、日本での有用性など6軸を公開検証中です。現在、掲載順には使用していません。
- AI関連度
- 90
- 情報源の信頼性
- 25
- 新規性
- 75
- 検索具体性
- 75
- 重複の少なさ
- 100
- 日本での有用性
- 25
記事は OpenSpace という具体的なツールを用いたエージェントの構築・進化プロセスを技術的に詳述しており、再現可能な実装知見が含まれるため technical_analysis に分類されます。また、Claude Sonnet 4.5 や MCP といった具体名が明記されているため検索機会スコアも高く設定されています。
キーポイント
自己進化型エージェントのアーキテクチャ
OpenSpace は環境設定からタスク実行、スキル進化までを含む一連のワークフローを提供し、SQLite を用いてバージョン管理付きで進化した能力を永続的に保存します。
MCP とスキルの統合による拡張性
ホストエージェントとのスキル接続やストリーミング HTTP MCP サーバーの起動により、FIX(修正)、DERIVED(派生)、CAPTURED(捕捉)という3つのスキルタイプを通じて柔軟な振る舞いを定義できます。
低コストでの再利用と最適化
スパースリポジトリのクローンや編集モードでのインストール、そして既存スキルの再利用機能により、開発コストを抑制しつつ効率的なエージェント運用を実現します。
OpenSpace のセットアップと依存関係
Python 3.12 以上が必要であり、Git を使用してリポジトリをクローンし、必要なパッケージ(nest_asyncio など)をインストールして環境を整備します。
環境変数による構成管理
モデル指定や API キー、スキルディレクトリのパスなどを .env ファイルに設定し、エージェントが実行する際に必要なコンテキストを動的に読み込む仕組みを実装しています。
LLM キーの有無による実行制御
API キーが設定されていない場合、ライブ実行ステップ(4/6)はスキップされるよう設計されており、キーの存在を確認して処理を分岐させています。
OpenSpace の環境構築と実行
Python ランタイムの検証、API クレデンシャルの設定、リポジトリのスプースチェックアウトによるインストールを行い、OpenSpace コマンドラインツールの利用可能性を確認する手順が含まれています。
重要な引用
progressing from environment setup and sparse repository cloning to live task execution, skill evolution, and MCP-based agent integration
analyze the showcase evolution database to understand how FIX, DERIVED, and CAPTURED skills support lower-cost, reusable agent behavior
"OpenSpace needs Python 3.12+, Colab has {sys.version}. Runtime > Change runtime type, or use a fallback py312 venv."
"No LLM key set — Steps 4/6 (live execution) will be skipped."
"We verify the Python runtime, define the required API credentials, and configure the OpenSpace model and optional cloud access settings."
"for skill in result.get('evolved_skills', []): print(f' Evolved: {skill['name']} (origin={skill['origin']})')"
影響分析・編集コメントを表示
影響分析
この記事は、単なるスクリプトの実行を超えて、AI エージェントが自律的にスキルを習得・進化させ、それを体系的に管理・再利用する実用的なフレームワークを示しています。特に MCP プロトコルとの統合と低コストでの運用可能性は、企業レベルでの大規模エージェント展開における開発効率と保守性を劇的に向上させる可能性があります。
編集コメント
エージェントの自律的な進化と、その履歴を詳細に管理できる機能は、実運用における信頼性向上に寄与する重要なステップです。MCP プロトコルとの親和性を高めたことで、開発者が既存エコシステムをそのまま活用しながら高度なエージェントを構築できる道が開かれました。
本チュートリアルでは、OpenSpace を用いたワークフローの構築と検証を行います。環境設定やリポジトリのクローンから始まり、ライブタスクの実行、スキルの進化、そして MCP ベースのエージェント統合へと段階的に進んでいきます。
まずモデル認証情報やワークスペース変数の設定を行い、プロジェクトを編集可能なモードでインストールします。その後、非同期 Python API を呼び出して、OpenSpace が SQLite 上でどのようにバージョン管理と系譜(ラインージ)メタデータを付与しながら進化させた能力を保存するかを検証します。
さらに、カスタム SKILL.md の作成やホストエージェントとのスキル連携、ウォームタスクの再利用テスト、ストリーミング対応 HTTP MCP サーバーの起動を行います。最後にショーケース用データベースを分析し、FIX(修正)、DERIVED(派生)、CAPTURED(捕捉)という 3 つのスキルタイプが、低コストで再利用可能なエージェント行動を実現する仕組みを理解します。
import os, sys, subprocess, sqlite3, json, textwrap, shutil, time, pathlib
ANTHROPIC_API_KEY = ""
OPENAI_API_KEY = ""
OPENSPACE_MODEL = "anthropic/claude-sonnet-4-5"
OPENSPACE_CLOUD_KEY = ""
assert sys.version_info >= (3, 12), (
f"OpenSpace needs Python 3.12+, Colab has {sys.version}. "
"Runtime > Change runtime type, or use a fallback py312 venv."
)
print("
image Python:", sys.version.split()[0])
REPO_DIR = "/content/OpenSpace"
if not os.path.exists(REPO_DIR):
subprocess.run(
["git", "clone", "--filter=blob:none", "--sparse",
"https://github.com/HKUDS/OpenSpace.git", REPO_DIR],
check=True,
)
subprocess.run(
["git", "sparse-checkout", "set", "--no-cone", "/*", "!/assets/"],
cwd=REPO_DIR, check=True,
)
print("
image Cloned to", REPO_DIR)
print("Top-level:", sorted(os.listdir(REPO_DIR)))
subprocess.run([sys.executable, "-m", "pip", "install", "-q", "-e", REPO_DIR], check=True)
subprocess.run([sys.executable, "-m", "pip", "install", "-q", "nest_asyncio"], check=True)
for cli in ["openspace-mcp", "openspace-dashboard"]:
path = shutil.which(cli)
print(f"{'
image' if path else '
image '} {cli}: {path}")
subprocess.run(["openspace-mcp", "--help"], check=False)
WORKSPACE = "/content/openspace_workspace"
SKILLS_DIR = "/content/my_agent_skills"
os.makedirs(WORKSPACE, exist_ok=True)
os.makedirs(SKILLS_DIR, exist_ok=True)
env_lines = [
f"OPENSPACE_MODEL={OPENSPACE_MODEL}",
f"OPENSPACE_WORKSPACE={WORKSPACE}",
f"OPENSPACE_HOST_SKILL_DIRS={SKILLS_DIR}",
]
if ANTHROPIC_API_KEY: env_lines.append(f"ANTHROPIC_API_KEY={ANTHROPIC_API_KEY}")
if OPENAI_API_KEY: env_lines.append(f"OPENAI_API_KEY={OPENAI_API_KEY}")
if OPENSPACE_CLOUD_KEY: env_lines.append(f"OPENSPACE_API_KEY={OPENSPACE_CLOUD_KEY}")
env_path = os.path.join(REPO_DIR, "openspace", ".env")
pathlib.Path(env_path).write_text("\n".join(env_lines) + "\n")
pathlib.Path("/content/.env").write_text("\n".join(env_lines) + "\n")
for line in env_lines:
k, _, v = line.partition("=")
os.environ[k] = v
print("
image .env written:\n" + "\n".join(l.split("=")[0] + "=***" if "KEY" in l else l for l in env_lines))
HAS_LLM_KEY = bool(ANTHROPIC_API_KEY or OPENAI_API_KEY)
if not HAS_LLM_KEY:
print("
image No LLM key set — Steps 4/6 (live execution) will be skipped.")
Python の実行環境を検証し、必要な API 認証情報を定義して OpenSpace モデルとオプションのクラウドアクセス設定を構成します。リポジトリはスパースチェックアウトでクローンし、パッケージを編集可能モード(editable mode)でインストールして、OpenSpace コマンドラインツールが利用可能か確認します。その後、ワークスペースとスキルディレクトリを作成し、環境設定ファイルを記述、必要な変数をエクスポート、そしてライブ LLM 実行が有効化されているかどうかを検出します。
Copy CodeCopiedUse a different Browser
import asyncio, nest_asyncio
nest_asyncio.apply()
async def run_task(query: str):
from openspace import OpenSpace
async with OpenSpace() as cs:
result = await cs.execute(query)
print("── RESPONSE " + "─" * 50)
print(result["response"][:3000])
for skill in result.get("evolved_skills", []):
print(f"
image Evolved: {skill['name']} (origin={skill['origin']})")
return result
if HAS_LLM_KEY:
result_1 = asyncio.run(run_task(
"Write a Python function that parses a CSV of employee hours and "
"computes weekly payroll with overtime (1.5x beyond 40h). Test it "
"on a small synthetic example and show the output."
))
else:
print("
image Skipped live task (no key).")
def dump_db(db_path, max_rows=8):
if not os.path.exists(db_path):
print("No DB at", db_path); return
con = sqlite3.connect(db_path)
cur = con.cursor()
tables = [r[0] for r in cur.execute(
"SELECT name FROM sqlite_master WHERE type='table'").fetchall()]
print(f"
image {db_path}\n tables: {tables}")
for t in tables:
try:
cols = [c[1] for c in cur.execute(f"PRAGMA table_info({t})").fetchall()]
rows = cur.execute(f"SELECT * FROM {t} LIMIT {max_rows}").fetchall()
print(f"\n
image {t} ({len(rows)} shown) cols={cols[:8]}{'…' if len(cols)>8 else ''}")
for r in rows:
print(" ", str(r)[:160])
except Exception as e:
print(f" (skip {t}: {e})")
con.close()
runtime_db = os.path.join(WORKSPACE, ".openspace", "openspace.db")
alt_db = os.path.join(REPO_DIR, ".openspace", "openspace.db")
dump_db(runtime_db if os.path.exists(runtime_db) else alt_db)
try:
from openspace.skill_engine.registry import SkillRegistry
from openspace.skill_engine import types as sk_types
print("\n
image skill_engine importable:",
[n for n in dir(sk_types) if n[0].isupper()][:6])
except Exception as e:
print("
image registry import note:", e)
Google Colab で非同期実行を初期化し、OpenSpace Python API を通じてタスクを送信するための再利用可能な関数を定義します。まず給与計算生成の初期タスクを実行し、事後分析で OpenSpace が進化させたスキルを確認します。さらに SQLite データベースの構造を検証し、保存されたレコードを表示。スキルレジストリと型定義がプログラムからアクセス可能か検証します。
LLM キーが存在する場合は、以下のタスクを実行します。
payroll ロジックを拡張し、従業員ごとの税額控除率を示す第 2 の CSV ファイルを追加して手取り給与を算出します。既存の payroll スキルも再利用してください。
run_task を非同期で実行した結果を result_2 に格納し、ランタイムデータベース(存在すればそれを、なければ代替用データベース)に最大 12 行分ダンプします。
LLM キーがない場合は、ウォームアップ再実行デモをスキップした旨を表示します。
次に、カスタムスキル用のディレクトリ「colab-csv-report」を作成します。存在しない場合は親ディレクトリも一緒に作成されます。
このディレクトリに SKILL.md ファイルを生成し、以下の内容を書き込みます。
name: colab-csv-report
description: 任意の CSV を読み込み、要約統計、null 値の数、データ型、および重要な観察点 3 つを含む短い Markdown レポートを作成します。pandas を使用しますが、プロットは行いません。
colab-csv-report
- pandas で CSV を読み込みます(エラー時は「on_bad_lines="skip"」でフォールバック)。
- 形状、データ型テーブル、describe() 結果、null 値の数を出力します。
- Markdown の箇条書き形式で重要な観察点 3 つを記述します。
- パースに失敗した場合は、「sep=None, engine="python"」で再試行します。
カスタムスキルの作成が完了しました。ファイルは「colab-csv-report/SKILL.md」です。
次に、ホストスキル(delegate-task と skill-discovery)をエージェントディレクトリにインストールします。REPO_DIR 内の openspace/host_skills ディレクトリから該当フォルダを検索し、SKILLS_DIR にコピーします。既に存在する場合は上書きせず、新規作成のみ行います。
ホストスキルのインストールが完了しました。SKILLS_DIR 内に以下のファイルが配置されています:delegate-task, skill-discovery。
最後に、LLM キーが存在する場合に限り、デモ用 CSV ファイル(/content/demo.csv)を作成し、以下のデータを書き込みます。
name,dept,hours,rate
Ada,Eng,45,90
Grace,Eng,38,95
Alan,Math,50,80
その後、colab-csv-report スキルを使用して、この CSV ファイルの Markdown レポートを生成するタスクを実行します。
OpenSpace が以前に生成されたスキルから能力をどのように再利用・派生させるかを観察するため、関連する給与計算タスクを実行しました。まず、CSV ファイルの分析と構造化された Markdown レポートの作成を指示するカスタム SKILL.md を作成します。その後、OpenSpace のホストスキルをインストールし、デモンストレーション用データセットを生成して、同じ進化型エージェントワークフローを通じてこのカスタム機能を実行します。
mcp_proc = subprocess.Popen(
["openspace-mcp", "--transport", "streamable-http",
"--host", "127.0.0.1", "--port", "8081"],
stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True,
env={**os.environ},
)
time.sleep(8)
try:
import urllib.request
req = urllib.request.Request("http://127.0.0.1:8081/mcp", method="GET")
try:
urllib.request.urlopen(req, timeout=5)
print("
image MCP streamable-HTTP endpoint is up at http://127.0.0.1:8081/mcp")
except urllib.error.HTTPError as e:
print(f"
image MCP server alive (HTTP {e.code} on bare GET, expected for MCP)")
except Exception as e:
print("
image MCP probe failed:", e)
print(json.dumps({
"mcpServers": {
"openspace": {
"command": "openspace-mcp",
"toolTimeout": 600,
"env": {
"OPENSPACE_HOST_SKILL_DIRS": SKILLS_DIR,
"OPENSPACE_WORKSPACE": WORKSPACE,
"OPENSPACE_API_KEY": "sk-xxx (optional, for cloud)",
},
}
}
}, indent=2))
mcp_proc.terminate()
必ずJSON形式で返してください。translation フィールドのみ。他のフィールドは一切追加しないこと — 余計なフィールドを書こうとして本文がトークン上限で打ち切られる事故を防ぐため:
{"translation": "リライト全文"}
OpenSpace の MCP サーバーは、ストリーミング HTTP トランスポートを使用して起動し、ローカルの Colab エンドポイントにバインドします。サーバープロセスが稼働していることを確認するためにエンドポイントをプローブしますが、これは基本的な HTTP リクエストに対して MCP 固有の応答ステータスが返される場合でも同様です。また、外部エージェントが OpenSpace のワークスペースやスキルディレクトリにアクセスできるよう、MCP ホスト設定の例も生成します。
OPENSPACE_CLOUD_KEY が設定されている場合、カスタムスキルをクラウドにアップロードするコマンドを実行し、完了のメッセージを表示します。キーが未設定の場合は、アップロード・ダウンロード機能の有効化に必要な環境変数の設定を促すメッセージが表示されます。
次に、リポジトリ内の showcase ディレクトリにある SQLite データベース(openspace.db)をダンプします。データベースが存在する場合、接続して各テーブルの構造を確認し、「origin」という列が含まれているテーブルについて、その値ごとの行数を集計・表示します。これにより、進化モードにおけるデータの内訳が把握できます。
最後に、チュートリアルの完了メッセージを表示します。これで以下が実現しています:
- Colab 環境に OpenSpace がインストールされ、設定済み
- Python API を介したリアルタイムタスク実行(キー設定時)
- エージェントが自動的に検出するカスタム SKILL.md の作成
- Claude Code、Codex、OpenClaw、nanobot など、SKILL.md に準拠するあらゆるエージェントで利用可能なホストスキル(delegate-task、skill-discovery)の準備完了
- ストリーミング HTTP を介して起動した MCP サーバー
- 60 以上のスキル進化履歴を記録したデータベースの完全な系譜調査機能
次は、関連タスクを実行し、スキルが自動的に修正・派生・キャプチャされることでトークン使用量が減少する様子を確認してください。ダッシュボード(Node.js バージョン 20 以上が必要)は以下のコマンドで起動できます:
openspace-dashboard --port 7788
その後、フロントエンドディレクトリに移動し、依存関係をインストールして開発サーバーを起動します。
cd frontend && npm i && npm run dev
有効なクラウド API キーが存在する場合、カスタムスキルを OpenSpace クラウドコミュニティへ条件付きでアップロードします。また、リポジトリに格納されたスキルの展示用 SQLite データベースを検証し、保存されているスキルやメタデータ、品質情報、そして完全な進化の系譜(ラインジ)を調査しました。
最後に、スキルの起源タイプごとに集約し、本チュートリアルを通じて構築した Colab 環境、カスタム機能、MCP(Model Context Protocol)の統合、そして自己進化するワークフローについて要約します。
結論として、エージェントの機能がどのように実行され、永続化され、再利用され、段階的に改善されるかを示す実用的な OpenSpace 環境を構築しました。Python API、ローカルのスキルディレクトリ、SQLite ベースのレジストリ、MCP トランスポート、そしてオプションのクラウド共有コマンドに直接取り組むことで、ユーザー向けのワークフローと背後にあるスキルエンジンアーキテクチャの両方を可視化できました。
さらに、関連タスクが以前に進化した知識をどのように再利用できるか、カスタムスキルがランタイム時にどのように検出可能になるか、そして各機能の開発履歴をラインジ記録がどのように明らかにするかを検証しました。これにより、Colab 上で自己進化しコスト効率の高いエージェントシステムを構築するための堅固な基盤が得られました。
完全なコードはこちらで確認できます。また、Twitter でフォローしていただくこともお気軽にどうぞ。忘れずに 15 万人以上の ML 専門家が参加する SubReddit に加入し、ニュースレターも購読してください。あ、Telegram も使っていますか?今なら Telegram でも私たちに参加いただけます。
GitHub リポジトリや Hugging Face のページ、製品リリース、ウェビナーなどのプロモーションをご希望の場合は、ぜひパートナーシップを構築してください。お気軽にご連絡ください。
本記事「スキル、MCP、ラインージ、低コスト再利用を活用した自己進化型 AI エージェントの構築(OpenSpace 編)」は、MarkTechPost で最初に公開されました。
原文を表示
In this tutorial, we build and examine an OpenSpace workflow, progressing from environment setup and sparse repository cloning to live task execution, skill evolution, and MCP-based agent integration. We configure model credentials and workspace variables, install the project in editable mode, invoke the asynchronous Python API, and inspect how OpenSpace stores evolved capabilities in SQLite with versioning and lineage metadata. We also create a custom SKILL.md, connect host-agent skills, test warm-task reuse, launch the streamable HTTP MCP server, and analyze the showcase evolution database to understand how FIX, DERIVED, and CAPTURED skills support lower-cost, reusable agent behavior.
Copy CodeCopiedUse a different Browser
import os, sys, subprocess, sqlite3, json, textwrap, shutil, time, pathlib
ANTHROPIC_API_KEY = ""
OPENAI_API_KEY = ""
OPENSPACE_MODEL = "anthropic/claude-sonnet-4-5"
OPENSPACE_CLOUD_KEY = ""
assert sys.version_info >= (3, 12), (
f"OpenSpace needs Python 3.12+, Colab has {sys.version}. "
"Runtime > Change runtime type, or use a fallback py312 venv."
)
print("
image Python:", sys.version.split()[0])
REPO_DIR = "/content/OpenSpace"
if not os.path.exists(REPO_DIR):
subprocess.run(
["git", "clone", "--filter=blob:none", "--sparse",
"https://github.com/HKUDS/OpenSpace.git", REPO_DIR],
check=True,
)
subprocess.run(
["git", "sparse-checkout", "set", "--no-cone", "/*", "!/assets/"],
cwd=REPO_DIR, check=True,
)
print("
image Cloned to", REPO_DIR)
print("Top-level:", sorted(os.listdir(REPO_DIR)))
subprocess.run([sys.executable, "-m", "pip", "install", "-q", "-e", REPO_DIR], check=True)
subprocess.run([sys.executable, "-m", "pip", "install", "-q", "nest_asyncio"], check=True)
for cli in ["openspace-mcp", "openspace-dashboard"]:
path = shutil.which(cli)
print(f"{'
image' if path else '
image '} {cli}: {path}")
subprocess.run(["openspace-mcp", "--help"], check=False)
WORKSPACE = "/content/openspace_workspace"
SKILLS_DIR = "/content/my_agent_skills"
os.makedirs(WORKSPACE, exist_ok=True)
os.makedirs(SKILLS_DIR, exist_ok=True)
env_lines = [
f"OPENSPACE_MODEL={OPENSPACE_MODEL}",
f"OPENSPACE_WORKSPACE={WORKSPACE}",
f"OPENSPACE_HOST_SKILL_DIRS={SKILLS_DIR}",
]
if ANTHROPIC_API_KEY: env_lines.append(f"ANTHROPIC_API_KEY={ANTHROPIC_API_KEY}")
if OPENAI_API_KEY: env_lines.append(f"OPENAI_API_KEY={OPENAI_API_KEY}")
if OPENSPACE_CLOUD_KEY: env_lines.append(f"OPENSPACE_API_KEY={OPENSPACE_CLOUD_KEY}")
env_path = os.path.join(REPO_DIR, "openspace", ".env")
pathlib.Path(env_path).write_text("\n".join(env_lines) + "\n")
pathlib.Path("/content/.env").write_text("\n".join(env_lines) + "\n")
for line in env_lines:
k, _, v = line.partition("=")
os.environ[k] = v
print("
image .env written:\n" + "\n".join(l.split("=")[0] + "=***" if "KEY" in l else l for l in env_lines))
HAS_LLM_KEY = bool(ANTHROPIC_API_KEY or OPENAI_API_KEY)
if not HAS_LLM_KEY:
print("
image No LLM key set — Steps 4/6 (live execution) will be skipped.")
We verify the Python runtime, define the required API credentials, and configure the OpenSpace model and optional cloud access settings. We clone the repository with sparse checkout, install the package in editable mode, and confirm that the OpenSpace command-line tools are available. We then create the workspace and skill directories, write the environment configuration files, export the required variables, and detect whether live LLM execution is enabled.
Copy CodeCopiedUse a different Browser
import asyncio, nest_asyncio
nest_asyncio.apply()
async def run_task(query: str):
from openspace import OpenSpace
async with OpenSpace() as cs:
result = await cs.execute(query)
print("── RESPONSE " + "─" * 50)
print(result["response"][:3000])
for skill in result.get("evolved_skills", []):
print(f"
image Evolved: {skill['name']} (origin={skill['origin']})")
return result
if HAS_LLM_KEY:
result_1 = asyncio.run(run_task(
"Write a Python function that parses a CSV of employee hours and "
"computes weekly payroll with overtime (1.5x beyond 40h). Test it "
"on a small synthetic example and show the output."
))
else:
print("
image Skipped live task (no key).")
def dump_db(db_path, max_rows=8):
if not os.path.exists(db_path):
print("No DB at", db_path); return
con = sqlite3.connect(db_path)
cur = con.cursor()
tables = [r[0] for r in cur.execute(
"SELECT name FROM sqlite_master WHERE type='table'").fetchall()]
print(f"
image {db_path}\n tables: {tables}")
for t in tables:
try:
cols = [c[1] for c in cur.execute(f"PRAGMA table_info({t})").fetchall()]
rows = cur.execute(f"SELECT * FROM {t} LIMIT {max_rows}").fetchall()
print(f"\n
image {t} ({len(rows)} shown) cols={cols[:8]}{'…' if len(cols)>8 else ''}")
for r in rows:
print(" ", str(r)[:160])
except Exception as e:
print(f" (skip {t}: {e})")
con.close()
runtime_db = os.path.join(WORKSPACE, ".openspace", "openspace.db")
alt_db = os.path.join(REPO_DIR, ".openspace", "openspace.db")
dump_db(runtime_db if os.path.exists(runtime_db) else alt_db)
try:
from openspace.skill_engine.registry import SkillRegistry
from openspace.skill_engine import types as sk_types
print("\n
image skill_engine importable:",
[n for n in dir(sk_types) if n[0].isupper()][:6])
except Exception as e:
print("
image registry import note:", e)
We initialize asynchronous execution in Google Colab and define a reusable function to submit tasks via the OpenSpace Python API. We run an initial payroll-generation task and inspect any skills that OpenSpace evolves during post-execution analysis. We also examine the SQLite database structure, display stored records, and verify that the skill registry and type definitions are accessible programmatically.
Copy CodeCopiedUse a different Browser
if HAS_LLM_KEY:
result_2 = asyncio.run(run_task(
"Extend the payroll logic: add a second CSV of tax withholding rates "
"per employee and produce net pay. Reuse any prior payroll skill."
))
dump_db(runtime_db if os.path.exists(runtime_db) else alt_db, max_rows=12)
else:
print("
image Skipped warm-rerun demo (no key).")
custom = pathlib.Path(SKILLS_DIR) / "colab-csv-report"
custom.mkdir(parents=True, exist_ok=True)
(custom / "SKILL.md").write_text(textwrap.dedent("""\
name: colab-csv-report
description: Turn any CSV into a short markdown report with summary stats,
null counts, dtypes, and 3 key observations. Use pandas; never plot.
# colab-csv-report
- Load the CSV with pandas (
on_bad_lines="skip"fallback). - Emit: shape, dtypes table, describe(), null counts.
- Write 3 bullet observations in plain markdown.
- If parsing fails, retry with
sep=None, engine="python".
"""))
print("
image Custom skill written:", custom / "SKILL.md")
for host_skill in ["delegate-task", "skill-discovery"]:
src = os.path.join(REPO_DIR, "openspace", "host_skills", host_skill)
dst = os.path.join(SKILLS_DIR, host_skill)
if os.path.isdir(src) and not os.path.isdir(dst):
shutil.copytree(src, dst)
print("
image Host skills installed into agent dir:", sorted(os.listdir(SKILLS_DIR)))
if HAS_LLM_KEY:
df_csv = "/content/demo.csv"
pathlib.Path(df_csv).write_text(
"name,dept,hours,rate\nAda,Eng,45,90\nGrace,Eng,38,95\nAlan,Math,50,80\n")
asyncio.run(run_task(
f"Using the colab-csv-report skill, produce a markdown report for {df_csv}"))
We submit a related payroll task to observe how OpenSpace reuses or derives capabilities from previously generated skills. We create a custom SKILL.md that instructs the agent to analyze CSV files and produce structured Markdown reports. We then install the OpenSpace host skills, generate a demonstration dataset, and execute the custom capability through the same evolving agent workflow.
Copy CodeCopiedUse a different Browser
mcp_proc = subprocess.Popen(
["openspace-mcp", "--transport", "streamable-http",
"--host", "127.0.0.1", "--port", "8081"],
stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True,
env={**os.environ},
)
time.sleep(8)
try:
import urllib.request
req = urllib.request.Request("http://127.0.0.1:8081/mcp", method="GET")
try:
urllib.request.urlopen(req, timeout=5)
print("
image MCP streamable-HTTP endpoint is up at http://127.0.0.1:8081/mcp")
except urllib.error.HTTPError as e:
print(f"
image MCP server alive (HTTP {e.code} on bare GET, expected for MCP)")
except Exception as e:
print("
image MCP probe failed:", e)
print(json.dumps({
"mcpServers": {
"openspace": {
"command": "openspace-mcp",
"toolTimeout": 600,
"env": {
"OPENSPACE_HOST_SKILL_DIRS": SKILLS_DIR,
"OPENSPACE_WORKSPACE": WORKSPACE,
"OPENSPACE_API_KEY": "sk-xxx (optional, for cloud)",
},
}
}
}, indent=2))
mcp_proc.terminate()
We start the OpenSpace MCP server using the streamable HTTP transport and bind it to a local Colab endpoint. We probe the endpoint to confirm that the server process is running, even when a basic HTTP request returns an MCP-specific response status. We also generate an example MCP host configuration that external agents can use to access the OpenSpace workspace and skill directories.
Copy CodeCopiedUse a different Browser
if OPENSPACE_CLOUD_KEY:
subprocess.run(["openspace-upload-skill", str(custom)], check=False)
print("
image Cloud CLI demo executed (upload).")
else:
print("
image Cloud skipped — set OPENSPACE_CLOUD_KEY to enable "
"openspace-upload-skill / openspace-download-skill.")
showcase_db = os.path.join(REPO_DIR, "showcase", ".openspace", "openspace.db")
dump_db(showcase_db, max_rows=10)
if os.path.exists(showcase_db):
con = sqlite3.connect(showcase_db)
cur = con.cursor()
for t in [r[0] for r in cur.execute(
"SELECT name FROM sqlite_master WHERE type='table'")]:
cols = [c[1].lower() for c in cur.execute(f"PRAGMA table_info({t})")]
if "origin" in cols:
print(f"\n
image Evolution-mode breakdown in table '{t}':")
for origin, n in cur.execute(
f"SELECT origin, COUNT(*) FROM {t} GROUP BY origin ORDER BY 2 DESC"):
print(f" {origin:>10}: {n}")
con.close()
print("""
══════════════════════════════════════════════════════════════════
image TUTORIAL COMPLETE — what you now have:
• OpenSpace installed + configured in Colab
• Live task execution via the Python API (if key set)
• A custom SKILL.md your agent auto-discovers
• Host skills (delegate-task, skill-discovery) staged for any
SKILL.md-capable agent (Claude Code / Codex / OpenClaw / nanobot)
• An MCP server you booted over streamable HTTP
• Full lineage inspection of a 60+ skill evolution DB
Next: run more related tasks and watch token usage drop as skills
FIX / DERIVE / CAPTURE themselves. Dashboard (needs Node ≥ 20):
openspace-dashboard --port 7788 + cd frontend && npm i && npm run dev
══════════════════════════════════════════════════════════════════
""")
We conditionally upload the custom skill to the OpenSpace cloud community when a valid cloud API key is available. We inspect the repository’s showcase SQLite database to study the stored skills, metadata, quality information, and complete evolution lineage. We finally aggregate skills by origin type and summarize the Colab environment, custom capability, MCP integration, and self-evolving workflow that we establish throughout the tutorial.
In conclusion, we established a practical OpenSpace environment that demonstrates how agent capabilities are executed, persisted, reused, and progressively improved. We worked directly with the Python API, local skill directories, SQLite-backed registries, MCP transports, and optional cloud skill-sharing commands, giving us visibility into both the user-facing workflow and the underlying skill-engine architecture. We also verified how related tasks can reuse previously evolved knowledge, how custom skills become discoverable at runtime, and how lineage records expose the development history of each capability, leaving us with a strong foundation for building self-evolving, cost-efficient agent systems in Colab.
Check out the Full Code here. Also, feel free to follow us on Twitter and don’t forget to join our 150k+ML SubReddit and Subscribe to our Newsletter. Wait! are you on telegram? now you can join us on telegram as well.
Need to partner with us for promoting your GitHub Repo OR Hugging Face Page OR Product Release OR Webinar etc.? Connect with us
The post Building Self-Evolving AI Agents with OpenSpace Using Skills, MCP, Lineage, and Low-Cost Reuse appeared first on MarkTechPost.
関連記事
今日のまとめ
AI日報で今日の重要ニュースをまとめ読み