mcpField
G
gtm-setup

gtm-setup

github.com/aimonk2025マーケティング・グロース9116 回インストール35 週間前に更新
リポジトリ

gtm-setup について

gtm-setup は、Node.js プロジェクト向けに Google Tag Manager API の設定と検証を案内するスキルです。依存関係の導入から OAuth 認証、接続テストまでを扱います。

主な機能

  1. 01Node.js プロジェクトの前提条件確認
  2. 02googleapis の導入と検証
  3. 03Google Cloud と OAuth の設定案内
  4. 04GTM 設定ファイルとトークンの作成
  5. 05API アクセスと権限のテスト

活用シーン

  1. 01Node.js プロジェクトでの GTM API 利用準備
  2. 02GTM コンテナ用 OAuth 認証情報の設定
  3. 03既存の GTM API 接続の確認

インストール

コマンドをコピーしてターミナルで実行します。

$npx skills add https://github.com/aimonk2025/google-tag-manager-automation --skill gtm-setup

インストール後、Claude Code で/gtm-setupを入力して読み込まれたか確認します。

同梱ファイル

SKILL.md と一緒にインストールされる参考資料やスクリプト。

examples/
sample.md
references/
google-cloud-setup.md
scripts/
install-googleapis.js
oauth-authorize.js
test-connection.js
validate-prerequisites.js

詳細

GTM セットアップ - 技術的な前提条件

依存関係のインストールから API アクセスの検証まで、GTM API のセットアッププロセス全体を自動化します。

ワークフロー

フェーズ 1:前提条件の確認

ステップ 1.1:Node.js プロジェクトの確認

Verify package.json exists:
- If missing → Error: "This must be run in a Node.js project"
- If exists → Continue

ステップ 1.2:既存のセットアップの確認

Check for existing files:
- gtm-credentials.json → Already configured
- gtm-token.json → Already authorized
- gtm-config.json → Configuration exists

If all exist:
  → "GTM API already configured. Run validation to test connection."
  → Skip to Phase 6 (Validation)

If partial:
  → "Partial setup detected. Continuing from [step]..."
フェーズ 2:googleapis のインストール

ステップ 2.1:パッケージの自動インストール

Run: npm install googleapis --save

Monitor output for:
✓ Success → Continue
✗ Error → Display error, suggest manual installation

ステップ 2.2:インストールの確認

Check package.json dependencies:
- "googleapis": "^..." present → Success
- Missing → Retry or manual install
フェーズ 3:Google Cloud プロジェクトのセットアップ

ステップ 3.1:Cloud Console へのアクセス案内

Present clickable URLs:

Step 1: Create/Select Google Cloud Project
→ https://console.cloud.google.com/projectcreate

Step 2: Enable Google Tag Manager API
→ https://console.cloud.google.com/apis/library/tagmanager.googleapis.com

Step 3: Create OAuth 2.0 Credentials
→ https://console.cloud.google.com/apis/credentials

Wait for user confirmation at each step.

ステップ 3.2:OAuth 認証情報の設定

Guide user through credential creation:

1. Click "Create Credentials" → "OAuth client ID"
2. Application type: "Desktop app"
3. Name: "GTM Automation Script"
4. Click "Create"
5. Download JSON file

Prompt: "Download the credentials JSON file and save it in your project root."

ステップ 3.3:認証情報の保存

Ask user for downloaded file path:
→ "Where did you save the credentials file?"

Options:
a) File is in project root → Look for oauth2.keys.json or similar
b) User provides path → Copy to gtm-credentials.json
c) User pastes content → Write to gtm-credentials.json

Validate JSON structure:
- Has "installed" or "web" key
- Has "client_id", "client_secret", "redirect_uris"

If invalid → Error with specific issue
If valid → Save as gtm-credentials.json
フェーズ 4:GTM アカウントとコンテナの設定

ステップ 4.1:GTM 情報の収集

Guide user to find GTM details:

"Open Google Tag Manager: https://tagmanager.google.com"

Q1: What is your GTM Account ID?
→ Hint: In GTM, go to Admin. Account ID is shown at top (format: 1234567890)

Q2: What is your GTM Container ID?
→ Hint: In GTM, select container. Container ID shown at top (format: GTM-XXXXXX)

Validate inputs:
- Account ID: Must be numeric
- Container ID: Must start with "GTM-"

ステップ 4.2:設定ファイルの作成

Generate gtm-config.json:

{
  "accountId": "[user input]",
  "containerId": "[user input]",
  "containerPublicId": "[user input]"
}

Save to project root.

注:workspaceId は gtm-config.json に保存されません。gtm-implementation スキルは、GTM API を介して常にアクティブなワークスペースを動的に解決します。これにより、GTM UI でバージョンを公開するとワークスペースが削除され、新たに作成されることによる問題を防ぎます。

フェーズ 5:OAuth 認証

ステップ 5.1:認証 URL の生成

Using googleapis library, generate OAuth consent URL.

Present to user:
"
=== Authorization Required ===

Open this URL in your browser to authorize access:

[Long Google OAuth URL]

This will:
1. Ask you to sign in to Google
2. Show permissions requested (Read/Write GTM access)
3. Redirect to a localhost URL with an authorization code

After authorizing, you'll see a page that says:
'The authentication flow has completed. You may close this window.'

Copy the FULL URL from your browser address bar.
"

ステップ 5.2:コードをトークンに交換

Prompt: "Paste the full redirect URL here:"

Extract authorization code from URL:
- URL format: http://localhost/?code=XXXX&scope=...
- Parse 'code' parameter

Exchange code for access/refresh tokens using OAuth2 client.

Save tokens to gtm-token.json:
{
  "access_token": "...",
  "refresh_token": "...",
  "scope": "...",
  "token_type": "Bearer",
  "expiry_date": 1234567890
}

Success message:
"✓ Authorization complete! Tokens saved to gtm-token.json"
フェーズ 6:検証とテスト

ステップ 6.1:API 接続のテスト

Using saved credentials and token, make test API call:

GET /tagmanager/v2/accounts/{accountId}/containers/{containerId}

Expected responses:
✓ 200 OK → Success! Container details returned
✗ 401 Unauthorized → Token invalid, re-authorize
✗ 403 Forbidden → Missing permissions, check API enable
✗ 404 Not Found → Wrong account/container ID
✗ Other → Display error details

ステップ 6.2:権限の確認

Check API response for required permissions:

Required GTM API scopes:
- tagmanager.edit.containers
- tagmanager.readonly

If missing scopes:
→ Error: "Insufficient permissions. Re-authorize with correct scopes."
→ Restart Phase 5

ステップ 6.3:最終確認

Display success summary:

"
=== GTM API Setup Complete ===

✓ googleapis installed
✓ OAuth credentials configured (gtm-credentials.json)
✓ Access token obtained (gtm-token.json)
✓ GTM configuration saved (gtm-config.json)
✓ API connection validated

Account: [accountId]
Container: [containerPublicId]

Files created:
- gtm-credentials.json (OAuth credentials)
- gtm-token.json (Access token - DO NOT commit to git)
- gtm-config.json (GTM account/container info)

Next steps:
→ Add gtm-token.json to .gitignore
→ Invoke gtm-implementation skill to implement tracking

Ready to implement tracking? Invoke gtm-implementation skill.
"

スクリプト

自動化する手順には、次のスクリプトを使用します。

scripts/install-googleapis.js
// Auto-install googleapis package
const { execSync } = require('child_process');

try {
  console.log('Installing googleapis...');
  execSync('npm install googleapis --save', { stdio: 'inherit' });
  console.log('✓ googleapis installed successfully');
} catch (error) {
  console.error('✗ Installation failed:', error.message);
  process.exit(1);
}
scripts/validate-prerequisites.js
// Validate existing setup files
const fs = require('fs');
const path = require('path');

const files = {
  'package.json': { required: true, description: 'Node.js project' },
  'gtm-credentials.json': { required: false, description: 'OAuth credentials' },
  'gtm-token.json': { required: false, description: 'Access token' },
  'gtm-config.json': { required: false, description: 'GTM configuration' }
};

console.log('Validating prerequisites...\n');

let allValid = true;
let setupStatus = {
  credentials: false,
  token: false,
  config: false
};

for (const [filename, config] of Object.entries(files)) {
  const exists = fs.existsSync(path.join(process.cwd(), filename));

  if (filename === 'gtm-credentials.json' && exists) setupStatus.credentials = true;
  if (filename === 'gtm-token.json' && exists) setupStatus.token = true;
  if (filename === 'gtm-config.json' && exists) setupStatus.config = true;

  const status = exists ? '✓' : (config.required ? '✗' : '○');
  console.log(`${status} ${filename} - ${config.description}`);

  if (config.required && !exists) {
    allValid = false;
  }
}

console.log('\nSetup status:');
if (setupStatus.credentials && setupStatus.token && setupStatus.config) {
  console.log('✓ Complete setup detected');
  console.log('→ Run test-connection.js to validate');
} else if (setupStatus.credentials || setupStatus.token || setupStatus.config) {
  console.log('○ Partial setup detected');
  if (!setupStatus.credentials) console.log('  Missing: OAuth credentials');
  if (!setupStatus.token) console.log('  Missing: Access token');
  if (!setupStatus.config) console.log('  Missing: GTM configuration');
} else {
  console.log('○ No setup detected');
  console.log('→ Start from Phase 3 (Google Cloud setup)');
}

process.exit(allValid ? 0 : 1);
scripts/oauth-authorize.js
// OAuth authorization flow
const { google } = require('googleapis');
const fs = require('fs');
const path = require('path');
const readline = require('readline');

const SCOPES = ['https://www.googleapis.com/auth/tagmanager.edit.containers'];
const TOKEN_PATH = path.join(process.cwd(), 'gtm-token.json');
const CREDENTIALS_PATH = path.join(process.cwd(), 'gtm-credentials.json');

// Load credentials
const credentials = JSON.parse(fs.readFileSync(CREDENTIALS_PATH, 'utf8'));
const { client_secret, client_id, redirect_uris } = credentials.installed || credentials.web;

const oAuth2Client = new google.auth.OAuth2(client_id, client_secret, redirect_uris[0]);

// Generate auth URL
const authUrl = oAuth2Client.generateAuthUrl({
  access_type: 'offline',
  scope: SCOPES,
});

console.log('\n=== GTM API Authorization ===\n');
console.log('Open this URL in your browser to authorize:\n');
console.log(authUrl);
console.log('\nAfter authorization, copy the full redirect URL from your browser.\n');

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
});

rl.question('Paste the redirect URL here: ', (redirectUrl) => {
  rl.close();

  // Extract code from URL
  const url = new URL(redirectUrl);
  const code = url.searchParams.get('code');

  if (!code) {
    console.error('✗ No authorization code found in URL');
    process.exit(1);
  }

  // Exchange code for token
  oAuth2Client.getToken(code, (err, token) => {
    if (err) {
      console.error('✗ Error retrieving access token:', err);
      process.exit(1);
    }

    // Save token
    fs.writeFileSync(TOKEN_PATH, JSON.stringify(token, null, 2));
    console.log('\n✓ Token saved to', TOKEN_PATH);
    console.log('\n=== Authorization Complete ===\n');
    console.log('You can now use the GTM API.');
    console.log('\nIMPORTANT: Add gtm-token.json to .gitignore\n');
  });
});
scripts/test-connection.js
// Test GTM API connection
const { google } = require('googleapis');
const fs = require('fs');
const path = require('path');

const TOKEN_PATH = path.join(process.cwd(), 'gtm-token.json');
const CREDENTIALS_PATH = path.join(process.cwd(), 'gtm-credentials.json');
const CONFIG_PATH = path.join(process.cwd(), 'gtm-config.json');

// Check files exist
if (!fs.existsSync(CREDENTIALS_PATH)) {
  console.error('✗ gtm-credentials.json not found');
  process.exit(1);
}

if (!fs.existsSync(TOKEN_PATH)) {
  console.error('✗ gtm-token.json not found. Run oauth-authorize.js first.');
  process.exit(1);
}

if (!fs.existsSync(CONFIG_PATH)) {
  console.error('✗ gtm-config.json not found');
  process.exit(1);
}

// Load files
const credentials = JSON.parse(fs.readFileSync(CREDENTIALS_PATH, 'utf8'));
const token = JSON.parse(fs.readFileSync(TOKEN_PATH, 'utf8'));
const config = JSON.parse(fs.readFileSync(CONFIG_PATH, 'utf8'));

const { client_secret, client_id, redirect_uris } = credentials.installed || credentials.web;

// Create OAuth client
const oAuth2Client = new google.auth.OAuth2(client_id, client_secret, redirect_uris[0]);
oAuth2Client.setCredentials(token);

// Create GTM client
const tagmanager = google.tagmanager({ version: 'v2', auth: oAuth2Client });

console.log('\n=== Testing GTM API Connection ===\n');
console.log(`Account ID: ${config.accountId}`);
console.log(`Container ID: ${config.containerPublicId}\n`);

// Test API call
const path_url = `accounts/${config.accountId}/containers/${config.containerId}`;

tagmanager.accounts.containers.get({ path: path_url })
  .then(response => {
    console.log('✓ Connection successful!\n');
    console.log('Container details:');
    console.log(`  Name: ${response.data.name}`);
    console.log(`  Public ID: ${response.data.publicId}`);
    console.log(`  Usage Context: ${response.data.usageContext.join(', ')}\n`);
    console.log('=== Setup Verified ===\n');
    console.log('Ready to use GTM API!\n');
  })
  .catch(error => {
    console.error('✗ Connection failed\n');

    if (error.code === 401) {
      console.error('Error: Unauthorized (401)');
      console.error('→ Token may be expired. Run oauth-authorize.js again.\n');
    } else if (error.code === 403) {
      console.error('Error: Forbidden (403)');
      console.error('→ Check that GTM API is enabled in Google Cloud Console.\n');
    } else if (error.code === 404) {
      console.error('Error: Not Found (404)');
      console.error('→ Check account ID and container ID in gtm-config.json.\n');
    } else {
      console.error('Error:', error.message, '\n');
    }

    process.exit(1);
  });

参考資料

  • references/google-cloud-setup.md - スクリーンショット付きの詳細な Google Cloud Console セットアップガイド

重要なガイドライン

セキュリティのベストプラクティス
  1. トークンを絶対にコミットしないでください:

    • gtm-token.json を .gitignore に追加します
    • トークンには機密性の高いアクセス認証情報が含まれます
  2. 認証情報ファイルのセキュリティ:

    • gtm-credentials.json はコミットできます(デスクトップアプリタイプではシークレットが含まれないため)
    • ただし、セキュリティをさらに高めるため、.gitignore への追加を推奨します
  3. トークンの更新:

    • トークンの有効期限は 1 時間です
    • (含まれている)リフレッシュトークンを使って自動更新できます
    • googleapis が更新を自動的に処理します
よくある問題

問題:「googleapis not found」 → 解決策:npm install googleapis --save を実行します

問題:「Invalid redirect URI」 → 解決策:OAuth クライアントの種類が「Web application」ではなく「Desktop app」であることを確認します

問題:「403 Forbidden」 → 解決策:Google Cloud Console で GTM API を有効にします

問題:「404 Not Found」 → 解決策:アカウント ID とコンテナ ID が正しいことを確認します

問題:「Token expired」 → 解決策:oauth-authorize.js を再実行して、新しいトークンを取得します

問題:「Workspace not found」/スキルが予期せず新しいワークスペースを作成する → 原因:GTM は公開後にワークスペースを削除します。保存済みのワークスペース ID は古くなります。 → 解決策:スキルはワークスペースを動的に解決するようになりました。対応は不要です。

テスト

セットアップ後、次のコマンドで確認します。

node scripts/test-connection.js

想定される出力:

✓ Connection successful!

Container details:
  Name: My Website
  Public ID: GTM-XXXXXX
  Usage Context: web

=== Setup Verified ===

実行チェックリスト

  • package.json が存在する(Node.js プロジェクト)
  • googleapis がインストールされている
  • Google Cloud プロジェクトが作成されている
  • GTM API が有効になっている
  • OAuth 認証情報が作成され、ダウンロードされている
  • gtm-credentials.json が保存されている
  • GTM アカウント ID を取得している
  • GTM コンテナ ID を取得している
  • gtm-config.json が作成されている
  • OAuth 認証が完了している
  • gtm-token.json が保存されている
  • API 接続のテストが正常に完了している
  • gtm-token.json が .gitignore に追加されている

関連ファイル

  • examples/sample.md - 各フェーズの出力と作成ファイルを示すセットアップセッションの例

出力ファイル

  • gtm-credentials.json - OAuth 2.0 クライアント認証情報
  • gtm-token.json - アクセストークンとリフレッシュトークン(機密情報)
  • gtm-config.json - GTM アカウントとコンテナの設定

引き継ぎ

セットアップが正常に完了したら:

✓ GTM API configured and validated

Next step: Invoke gtm-implementation skill to:
- Implement dataLayer events in your code
- Create GTM variables, triggers, and tags via API

Ready to implement? Invoke gtm-implementation skill.

よくある質問

Q: 複数のプロジェクトで同じ認証情報を使用できますか? A: はい。gtm-credentials.json を他のプロジェクトにコピーしてください。各プロジェクトにはそれぞれ専用のトークン(gtm-token.json)が必要です。

Q: GTM コンテナが複数ある場合はどうすればよいですか? A: コンテナごとにセットアップを実行してください。異なる gtm-config.json ファイルを作成するか、異なるプロジェクトディレクトリを使用してください。

Q: Google Cloud の請求先アカウントは必要ですか? A: いいえ。GTM API は無料で使用できます。請求先アカウントは必要ありません。

Q: 後からアクセスを取り消せますか? A: はい。https://myaccount.google.com/permissions にアクセスし、「GTM Automation Script」へのアクセスを取り消してください。

Q: どのスコープを要求しますか? A: tagmanager.edit.containers - GTM コンテナへの読み取りおよび書き込みアクセスです。これにより、変数、トリガー、タグを作成・更新できます。

コメント