取り組みの背景 — この記事シリーズについて
Antigravity の基本を学んだら、次は「実践」の段階です。このシリーズでは、実際のプロジェクト開発で頻繁に使うテクニックを、コード例を交えて解説します。
前編(本記事)の内容
- Cmd+K の実践パターン
- エージェント機能の基本活用
- AGENTS.md の効果的な書き方
- Figma → コード変換の基本
- Next.js + Supabase の基本スキャフォールディング
後編(プレミアム記事)の内容
- マルチエージェント・オーケストレーション
- 本番品質のアプリ開発(SwiftUI・Android・Edge AI)
- カスタム MCP サーバー構築
- SaaS 収益化パイプライン
エディタ操作のベストプラクティス
Cmd+K の実践パターン(リファクタリング・テスト生成・型付け)
Cmd+K は単なるコード修正ツールではなく、戦略的に活用することで開発生産性が数倍に向上します。
パターン 1: TypeScript 型付け
シナリオ: 既存の JavaScript 関数を TypeScript に移行したい場合
Before
function calculateDiscount(price, discountPercent) {
return price * (1 - discountPercent / 100);
}Cmd+K のプロンプト
この関数を TypeScript で型付けして。price は number、discountPercent も number、返り値も number
After
function calculateDiscount(price: number, discountPercent: number): number {
return price * (1 - discountPercent / 100);
}パターン 2: テスト自動生成
シナリオ: 複雑な計算ロジックをテストしたい
Before
export function validateEmail(email: string): boolean {
const regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return regex.test(email) && email.length <= 254;
}Cmd+K のプロンプト
この関数の Jest テストをカバレッジ 100% で書いて。正常系・エッジケースをカバーして
After
describe('validateEmail', () => {
it('正常なメールアドレスを受け入れる', () => {
expect(validateEmail('user@example.com')).toBe(true);
});
it('メールアドレスなしを拒否', () => {
expect(validateEmail('invalid')).toBe(false);
});
it('254文字を超えるメールを拒否', () => {
expect(validateEmail('a'.repeat(250) + '@example.com')).toBe(false);
});
it('スペースを含むメールを拒否', () => {
expect(validateEmail('user name@example.com')).toBe(false);
});
});パターン 3: React コンポーネントの最適化
シナリオ: クラスコンポーネントを関数コンポーネント + Hooks に書き直す
Before
class UserProfile extends React.Component {
constructor(props) {
super(props);
this.state = { user: null, loading: true };
}
componentDidMount() {
fetch(`/api/users/${this.props.userId}`)
.then(r => r.json())
.then(user => this.setState({ user, loading: false }));
}
render() {
const { user, loading } = this.state;
return loading ? <div>Loading...</div> : <div>{user.name}</div>;
}
}Cmd+K のプロンプト
このクラスコンポーネントを React Hooks で書き直して。useEffect と useState を使用
After
function UserProfile({ userId }: { userId: string }) {
const [user, setUser] = React.useState<User | null>(null);
const [loading, setLoading] = React.useState(true);
React.useEffect(() => {
fetch(`/api/users/${userId}`)
.then(r => r.json())
.then(user => {
setUser(user);
setLoading(false);
});
}, [userId]);
return loading ? <div>Loading...</div> : <div>{user?.name}</div>;
}コードコンテキストの効率的な管理
Antigravity のチャット機能では、大量のコンテキストを参照できますが、効率的に管理しないと無駄なトークンを消費します。
Tips 1: 関連ファイルのみを開く
チャット開始前に、関連ファイルタブを開きましょう。Antigravity は開いているタブを優先的に参照します。
1. チャットで議論するコンポーネント
2. そのコンポーネントが import している utils
3. 型定義ファイル
→ これら 3 つだけを開く状態でチャット開始
Tips 2: AGENTS.md を常に最新に
AGENTS.md が古い状態だと、チャットで説明に時間を費やします。定期的に更新してください。
## Updated: 2026-03-20
最近のアーキテクチャ変更、新規エージェントの追加をここに記載Tips 3: インラインコンテキスト参照
大型ドキュメントは参照する行を明示的に指定:
チャットプロンプト:
「src/api/auth.ts の 45-60行目にある authenticateUser 関数について...」
エージェント機能の基本活用
Agent Manager の基本操作
Antigravity のエージェント機能は、複数の AI が同時に動作する「マルチエージェント・システム」です。
1. エージェント作成の流れ
Step 1: Agent Manager を開く
左サイドバー → Agent アイコン → 「新規エージェント」
Step 2: 役割を定義
名前: "Frontend Developer"
説明: "React コンポーネント・ページ実装を担当"
権限: src/components, src/app ディレクトリ
制限: src/api は編集禁止
Step 3: タスク割り当て
自然言語でタスクを指示:
「Dashboard ページを /app/dashboard に作成して。
TailwindCSS でレスポンシブデザイン。
データ取得は /api/analytics から」
Step 4: 実行・確認
実行ボタン → AI がファイル編集を開始 → 各ステップを確認・調整
2. エージェント間の協力
複数エージェントが同じプロジェクトで動作する場合:
Frontend Agent がコンポーネント作成
↓
Backend Agent が必要な API エンドポイントを実装
↓
Test Agent が E2E テストを生成
↓
Deploy Agent がビルド・デプロイ
各エージェントは AGENTS.md の定義に基づき、自動的に調整を行います。
AGENTS.md の効果的な書き方(テンプレート付き)
AGENTS.md は単なる ドキュメントではなく、エージェントの活動原則を定める指南書 です。
テンプレート: スタートアップ向け SaaS
# Antigravity SaaS Starter Template
## Project Overview
**プロジェクト名**: Analytics Dashboard SaaS
**目的**: 中小企業向けリアルタイム分析プラットフォーム
**ステータス**: MVP フェーズ(2026年3月)
## Tech Stack & Architecture
### Frontend
- Framework: Next.js 15 (App Router)
- Styling: TailwindCSS v4
- State: TanStack Query, Zustand
- Components: shadcn/ui
### Backend
- Runtime: Node.js 22
- Framework: Express.js
- Database: PostgreSQL (Supabase)
- Real-time: Supabase Realtime
### DevOps
- Hosting: Vercel (Frontend), Render (Backend)
- CI/CD: GitHub Actions
- Monitoring: Sentry
## Directory Structure
/app # Next.js アプリケーション /dashboard # メインダッシュボード /auth # 認証フロー /api # API Routes /lib # ユーティリティ・hooks /components # React コンポーネント /migrations # DB マイグレーション /tests # テストコード
## Agent Definitions
### Agent: Frontend Developer
**役割**
- React コンポーネント・ページの実装
- UI/UX の実装(デザイン仕様書に基づく)
- クライアント側のデータ管理
**権限**
- 読取: すべてのファイル
- 書込: /components, /app, /lib (client-side utilities)
**禁止事項**
- API Route (/app/api) 編集
- データベース マイグレーション実施
- 環境変数設定変更
**接続 MCP**
- Figma Dev Mode(デザインから自動コード生成)
**タスク例**
「Dashboard ページのチャートコンポーネントを実装。 Design: Figma の Dashboard Frame を参照。 Data: /api/analytics/monthly-stats から取得。 Responsive: モバイル対応(Tailwind breakpoints)」
### Agent: Backend Engineer
**役割**
- API Route 開発
- データベースロジック実装
- 認証・認可システム
**権限**
- 読取: すべてのファイル
- 書込: /app/api, /migrations, /lib (server-side utilities)
**禁止事項**
- React コンポーネント編集
- Figma ファイル編集
**接続 MCP**
- Supabase Admin (PostgreSQL, Auth)
- GitHub (コミット、PR 作成)
**タスク例**
「GET /api/analytics/monthly-stats エンドポイントを実装。 認証: Supabase Auth JWT 検証 Query: 過去 12 ヶ月の統計データ キャッシュ: Redis で 1 時間保持」
### Agent: QA Automation
**役割**
- E2E テスト自動生成・実行
- パフォーマンステスト
- デプロイ前チェック
**権限**
- 読取: すべてのファイル
- 書込: /tests
**接続 MCP**
- Browser Sub-Agent (Playwright)
- GitHub Actions
**タスク例**
「Dashboard ページの E2E テストを Playwright で作成。 シナリオ:
- ログイン
- Dashboard 表示
- チャート表示確認
- データフィルター動作確認
- ログアウト」
## Knowledge Items
### Design Specs
- Figma: https://figma.com/design/xxx
- Color System: Primary #0066FF, Secondary #666666
- Typography: Inter, Mono (coding)
### API Documentation
- OpenAPI Spec: /docs/openapi.json
- 認証: JWT Bearer Token(Supabase Auth)
- Rate Limit: 100 req/min
### Database Schema
```sql
CREATE TABLE users (
id UUID PRIMARY KEY,
email VARCHAR(255) NOT NULL UNIQUE,
created_at TIMESTAMP DEFAULT NOW()
);
CREATE TABLE analytics_events (
id UUID PRIMARY KEY,
user_id UUID REFERENCES users(id),
event_type VARCHAR(50),
data JSONB,
created_at TIMESTAMP DEFAULT NOW()
);
Deployment Checklist
- [ ] すべてテスト合格
- [ ] Environment variables 設定確認
- [ ] Database migration 実行
- [ ] Sentry integration 有効化
---
## デザイン→コードの基本ワークフロー
### Figma Dev Mode との連携基礎
Figma Dev Mode は、**デザイナーが作成したコンポーネントから自動的にコードを生成する** MCP です。
#### Step 1: Figma ファイルを準備
Figma で以下のように整理します:
Design System ├── Colors ├── Typography ├── Components │ ├── Button (Primary, Secondary, Disabled) │ ├── Input (Default, Error, Disabled) │ └── Card └── Screens └── Dashboard
#### Step 2: MCP を接続
Antigravity 設定で Figma Dev Mode MCP を認証:
Settings → MCP → Figma を追加 → API Key 入力 → Connect
#### Step 3: チャットから利用
Frontend Agent に指示: 「Figma ファイル(https://figma.com/design/xxx)の Button コンポーネント (Primary variant) を React コンポーネント化。 props: label (string), onClick (function), disabled (boolean)」
Antigravity が Figma から自動抽出し、React コンポーネント化します:
```typescript
// components/Button.tsx
export interface ButtonProps {
label: string;
onClick: () => void;
disabled?: boolean;
variant?: 'primary' | 'secondary';
}
export function Button({
label,
onClick,
disabled = false,
variant = 'primary',
}: ButtonProps) {
const baseStyles = 'px-4 py-2 rounded-lg font-medium transition';
const variantStyles = {
primary: 'bg-blue-600 text-white hover:bg-blue-700 disabled:bg-gray-400',
secondary: 'bg-gray-200 text-gray-900 hover:bg-gray-300 disabled:bg-gray-100',
};
return (
<button
className={`${baseStyles} ${variantStyles[variant]}`}
onClick={onClick}
disabled={disabled}
>
{label}
</button>
);
}
Google Stitch でUI デザインをコード化
Google Stitch は Google Workspace 統合 MCP です。
スプレッドシートから設定ジェネレータを作成
Google Sheets に機能リストを作成:
| Feature | Status | Assigned | Due Date |
|---------|--------|----------|----------|
| Login | In Progress | Frontend | 2026-03-25 |
| Dashboard | Not Started | Backend | 2026-03-30 |
Antigravity に指示:
「Google Sheets https://docs.google.com/spreadsheets/d/xxx
から読み込んで、AGENTS.md のタスクリストを自動更新」
基本的なアプリ開発パターン
Next.js + Supabase のスキャフォールディング
最初のプロジェクト構築は、Antigravity が自動化できます。
初期セットアップ指示
プロンプト
Next.js 15 + Supabase でブログプラットフォームを作成。
要件:
- ユーザー認証(Supabase Auth)
- ブログ記事一覧・詳細ページ
- 管理画面(記事作成・編集)
- TailwindCSS でスタイル
構成:
/app/page.tsx - トップページ
/app/blog/[id].tsx - ブログ詳細
/app/admin/posts.tsx - 管理画面
/app/api/posts.ts - API Route
/lib/supabase.ts - Supabase クライアント
Backend Agent が生成する内容
// lib/supabase.ts
import { createClient } from '@supabase/supabase-js';
export const supabase = createClient(
process.env.NEXT_PUBLIC_SUPABASE_URL!,
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!
);
export const supabaseAdmin = createClient(
process.env.NEXT_PUBLIC_SUPABASE_URL!,
process.env.SUPABASE_SERVICE_ROLE_KEY!
);// app/api/posts.ts
import { supabaseAdmin } from '@/lib/supabase';
export async function GET() {
const { data, error } = await supabaseAdmin
.from('posts')
.select('*')
.order('created_at', { ascending: false });
if (error) return new Response(JSON.stringify(error), { status: 500 });
return new Response(JSON.stringify(data), { status: 200 });
}
export async function POST(req: Request) {
const { title, content } = await req.json();
const { data, error } = await supabaseAdmin
.from('posts')
.insert([{ title, content, published: false }]);
if (error) return new Response(JSON.stringify(error), { status: 500 });
return new Response(JSON.stringify(data), { status: 201 });
}Unity C# コードの基本的なリファクタリング
ゲーム開発でも Antigravity が活躍します。
シナリオ: 古い MonoBehaviour を最新パターンに書き直す
Before
public class PlayerController : MonoBehaviour
{
public float speed = 5f;
private Rigidbody rb;
void Start()
{
rb = GetComponent<Rigidbody>();
}
void Update()
{
float h = Input.GetAxis("Horizontal");
float v = Input.GetAxis("Vertical");
rb.velocity = new Vector3(h * speed, rb.velocity.y, v * speed);
}
}Cmd+K のプロンプト
このコードを以下の改善パターンで書き直して:
1. InputManager パターンで入力管理を分離
2. SerializeField で設定値を可視化
3. GetComponent はキャッシュ
4. Quaternion.LookRotation で向き制御を追加
After
public class PlayerController : MonoBehaviour
{
[SerializeField] private float moveSpeed = 5f;
[SerializeField] private float rotationSpeed = 5f;
private Rigidbody rb;
private InputManager inputManager;
private void Awake()
{
rb = GetComponent<Rigidbody>();
inputManager = GetComponent<InputManager>();
}
private void FixedUpdate()
{
Vector3 input = inputManager.GetMovementInput();
MovePlayer(input);
RotatePlayer(input);
}
private void MovePlayer(Vector3 direction)
{
Vector3 velocity = direction * moveSpeed;
velocity.y = rb.velocity.y;
rb.velocity = velocity;
}
private void RotatePlayer(Vector3 direction)
{
if (direction.magnitude > 0.1f)
{
Quaternion targetRotation = Quaternion.LookRotation(direction);
transform.rotation = Quaternion.Lerp(
transform.rotation,
targetRotation,
Time.deltaTime * rotationSpeed
);
}
}
}次のステップ — 後編(プレミアム)で学べること
前編では 基本的なテクニック を網羅しました。
後編(プレミアム記事)では以下の 上級テクニック を解説します:
- マルチエージェント・オーケストレーション設計: ルーターパターン・パイプラインパターン
- 本番品質のアプリ開発: SwiftUI、Android、Edge AI
- カスタム MCP サーバー構築: TypeScript でツール拡張
- SaaS 収益化パイプライン: Stripe 統合、YouTube 動画自動制作、Kindle 執筆
Antigravity Lab のプレミアム会員になることで、実案件で使える高度なテクニックをすべて習得できます。