feat: cms_hospital_compare — CMS(메디케어) 병원 성과 데이터 조회/비교 도구

data.cms.gov "Hospital General Information" 공개 데이터셋(키 불필요)에서
소유형태(영리/비영리/정부)·CMS 종합별점(1~5)·사망률/안전/재입원 측정치의
전국평균 대비 better/worse 개수를 조회. compare=true면 소유형태별로 집계 —
"영리 vs 비영리 병원 성과" 질문에 근거 데이터 제공.

- registry.ts / build-tools.ts 양쪽에 등록
- tool-scope.ts: 병원 데이터 키워드 게이트 추가(상시 로드 안 함)
- retry-decisions.ts: GROUNDING_TOOL_PATTERN에 추가(검색 강제 재시도 방지)

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XZX9JHFSLZRuK9rR4sCVBs
This commit is contained in:
kimandClaude Sonnet 5 committed 2026-09-01 11:01:18 +09:00
1 parent 434dadf038
commit 82ca2999fc
5 files changed
+279 -1

No files matched your search

+19
View File
@@ -723,6 +723,25 @@ export function createBuildTools(isOrchestrationSkillEnabled: () => boolean) {
},
},
},
{
type: 'function',
function: {
name: 'cms_hospital_compare',
description: 'Look up or compare US hospitals using CMS (Medicare) Hospital General Information data: ownership (for-profit / non-profit / government), hospital type, CMS overall star rating (1–5), and counts of mortality / patient-safety / readmission measures scored better or worse than the national rate. Set compare=true to aggregate matching hospitals by ownership — use for "for-profit vs non-profit hospital performance" questions. No API key. US hospitals only; do NOT use web_search for this.',
parameters: {
type: 'object', required: [],
properties: {
name: { type: 'string', description: 'Hospital name substring (list mode)' },
state: { type: 'string', description: 'Two-letter US state/territory code, e.g. "CA", "TX"' },
city: { type: 'string', description: 'City name' },
ownership: { type: 'string', description: '"for-profit" | "non-profit" | "government", or a raw substring of the CMS ownership label' },
hospital_type: { type: 'string', description: 'e.g. "Acute Care Hospitals" (default when compare=true), "Critical Access Hospitals", "Psychiatric"' },
compare: { type: 'boolean', description: 'true → per-ownership aggregate stats instead of a hospital list' },
max_results: { type: 'number', description: 'List mode: max hospitals to return (1–60, default 20)' },
},
},
},
},
// Email tools
{
type: 'function',
+1 -1
View File
@@ -59,7 +59,7 @@ import {
// authoritative source it had just read. weather_* was already covered by prefix; these two were
// simply never added when they were written.
/** Tools that can actually ground a factual/live-data answer. Anything else does not count. */
export const GROUNDING_TOOL_PATTERN = /^(web_search|web_fetch|weather_|ollama_web_|news_search|memory_stats|nhc_active_storms|eonet_events|pubmed_search|pubmed_fetch|pubmed_fulltext|openalex_search|korean_law_search|korean_law_fetch|us_case_search|sqlite_query)/i;
export const GROUNDING_TOOL_PATTERN = /^(web_search|web_fetch|weather_|ollama_web_|news_search|memory_stats|nhc_active_storms|eonet_events|pubmed_search|pubmed_fetch|pubmed_fulltext|openalex_search|korean_law_search|korean_law_fetch|us_case_search|sqlite_query|cms_hospital_compare)/i;
export interface AutoRecoverInput {
/** The user's message this turn. */
+7
View File
@@ -87,6 +87,12 @@ export function buildSkillToolFilter(input: ToolScopeInput): (toolName: string)
// papers → create_presentation), not in standalone chat — gate them the same way as the
// pptx tools themselves rather than always loading 5 more schemas.
const academicToolNames = new Set(['pubmed_search', 'pubmed_fetch', 'pubmed_fulltext', 'openalex_search', 'semantic_search']);
// cms_hospital_compare — CMS Medicare hospital data (ownership / star rating / mortality /
// readmission). ~450-token schema, only relevant to US-hospital-performance questions, so
// gate it rather than carry it on every turn.
const hasHospitalDataKeyword =
/\bCMS\b|메디케어|\bmedicare\b|care\s*compare|hospital\s*compare|hospital\s*(rating|ratings|star|quality|ownership|performance)|병원.{0,6}(비교|평가|등급|순위|별점|소유|영리|비영리|성과|퀄리티|데이터)|(영리|비영리|투자자\s*소유).{0,4}병원|(for-?profit|non-?profit|nonprofit|investor-owned).{0,20}hospital/i
.test(message);
// coder_* (10 tools) is the file-authoring toolkit for actual code/script work — it has its
// own dedicated branch for isCodeAiSession (code.html) below, so this only affects the
// general chat path (main app + app-specific tabs like ac_/wt_/lw_/dental_/mn_, none of which
@@ -261,6 +267,7 @@ export function buildSkillToolFilter(input: ToolScopeInput): (toolName: string)
// Now matches the weather/legal shape directly above: exclude unless skill AND keyword agree.
if (pptxToolNames.has(name) && !(presenterEnabled && hasPptxKeyword)) return false;
if (academicToolNames.has(name) && !hasPptxKeyword && !hasAcademicKeyword) return false;
if (name === 'cms_hospital_compare' && !hasHospitalDataKeyword) return false;
if (emailToolNames.has(name) && !hasEmailKeyword) return false;
if (name === 'kakao_send_message' && !hasKakaoKeyword) return false;
if (name === 'sqlite_query' && !hasSqliteKeyword) return false;
+250
View File
@@ -0,0 +1,250 @@
import { ToolResult } from '../types.js';
// CMS Provider Data Catalog — "Hospital General Information" dataset.
// Public, no API key. One row per Medicare-certified hospital: ownership, type,
// CMS overall star rating (1–5), and roll-up counts of how many mortality /
// safety / readmission measures the hospital scored "better" / "no different" /
// "worse" than the national rate. Enough to compare, e.g., for-profit vs
// non-profit hospital performance without pulling every individual measure file.
//
// Datastore query API (DKAN): GET .../datastore/query/{id}/0
// conditions[i][property|value|operator], properties[i], limit (max 1500), offset
// schema=false keeps the response small; with `properties` set and schema=false
// each result comes back as a keyed object.
const DATASET_ID = 'xubh-q36u';
const BASE = `https://data.cms.gov/provider-data/api/1/datastore/query/${DATASET_ID}/0`;
const PAGE = 1500;
const MAX_PAGES = 6; // 9000 rows — the whole dataset is ~5400
const PROPS = [
'facility_name', 'citytown', 'state', 'hospital_type', 'hospital_ownership',
'hospital_overall_rating', 'emergency_services',
'count_of_mort_measures_better', 'count_of_mort_measures_worse',
'count_of_safety_measures_better', 'count_of_safety_measures_worse',
'count_of_readm_measures_better', 'count_of_readm_measures_worse',
];
type Row = Record<string, string>;
function ownershipBucket(raw: string): string {
const o = (raw || '').toLowerCase();
if (o.includes('proprietary')) return 'For-profit';
if (o.includes('non-profit') || o.includes('nonprofit')) return 'Non-profit';
if (o.includes('government') || o.includes('federal') || o.includes('veterans') ||
o.includes('defense') || o.includes('tribal')) return 'Government';
return 'Other';
}
function num(s: string | undefined): number | null {
return s != null && /^-?\d+$/.test(String(s)) ? Number(s) : null;
}
async function fetchPage(conditions: any[], offset: number): Promise<{ results: Row[]; count: number }> {
const p = new URLSearchParams();
p.set('limit', String(PAGE));
p.set('offset', String(offset));
p.set('schema', 'false');
conditions.forEach((c, i) => {
p.set(`conditions[${i}][property]`, c.property);
p.set(`conditions[${i}][value]`, c.value);
p.set(`conditions[${i}][operator]`, c.operator);
});
PROPS.forEach((prop, i) => p.set(`properties[${i}]`, prop));
const res = await fetch(`${BASE}?${p}`, {
signal: AbortSignal.timeout(20_000),
headers: { Accept: 'application/json', 'User-Agent': 'SmallClaw/1.0' },
});
if (!res.ok) throw new Error(`CMS HTTP ${res.status}: ${(await res.text().catch(() => '')).slice(0, 200)}`);
const data: any = await res.json();
return { results: data?.results ?? [], count: Number(data?.count ?? 0) };
}
async function fetchRows(conditions: any[]): Promise<{ rows: Row[]; total: number; truncated: boolean }> {
const first = await fetchPage(conditions, 0);
const rows = [...first.results];
const total = first.count;
const pages = Math.min(MAX_PAGES, Math.ceil(total / PAGE));
for (let pg = 1; pg < pages; pg++) {
const next = await fetchPage(conditions, pg * PAGE);
rows.push(...next.results);
}
return { rows, total, truncated: total > rows.length };
}
function summarize(rows: Row[]) {
const rated = rows.map(r => num(r.hospital_overall_rating)).filter((n): n is number => n != null);
const avg = rated.length ? rated.reduce((a, b) => a + b, 0) / rated.length : null;
const dist: Record<string, number> = { '1': 0, '2': 0, '3': 0, '4': 0, '5': 0 };
for (const n of rated) dist[String(n)]++;
const sum = (k: string) => rows.reduce((a, r) => a + (num(r[k]) || 0), 0);
return {
n: rows.length,
rated: rated.length,
avg_rating: avg == null ? null : Number(avg.toFixed(2)),
rating_dist: dist,
mort_better: sum('count_of_mort_measures_better'),
mort_worse: sum('count_of_mort_measures_worse'),
safety_better: sum('count_of_safety_measures_better'),
safety_worse: sum('count_of_safety_measures_worse'),
readm_better: sum('count_of_readm_measures_better'),
readm_worse: sum('count_of_readm_measures_worse'),
};
}
export const cmsHospitalCompareTool = {
name: 'cms_hospital_compare',
description:
'Look up or compare US hospitals using CMS (Medicare) Hospital General Information data: ' +
'ownership (for-profit / non-profit / government), hospital type, CMS overall star rating (1–5), ' +
'and counts of mortality / patient-safety / readmission measures scored better or worse than the ' +
'national rate. Set compare=true to aggregate matching hospitals by ownership category — useful for ' +
'"for-profit vs non-profit hospital performance" questions. No API key. US hospitals only.',
schema: {
name: 'Hospital name substring (list mode)',
state: 'Two-letter US state/territory code, e.g. "CA", "TX"',
city: 'City name',
ownership: '"for-profit" | "non-profit" | "government", or a raw substring of the CMS ownership label',
hospital_type: 'e.g. "Acute Care Hospitals" (default when compare=true), "Critical Access Hospitals", "Psychiatric"',
compare: 'true → return per-ownership aggregate stats instead of a hospital list',
max_results: 'List mode: max hospitals to return (1–60, default 20)',
},
jsonSchema: {
type: 'object',
properties: {
name: { type: 'string' },
state: { type: 'string' },
city: { type: 'string' },
ownership: { type: 'string' },
hospital_type: { type: 'string' },
compare: { type: 'boolean' },
max_results: { type: 'number' },
},
additionalProperties: false,
},
execute: async (args: any): Promise<ToolResult> => {
const compare = args?.compare === true || args?.compare === 'true';
const state = String(args?.state || '').trim().toUpperCase();
const city = String(args?.city || '').trim();
const name = String(args?.name || '').trim();
const ownRaw = String(args?.ownership || '').trim().toLowerCase();
let hospitalType = String(args?.hospital_type || '').trim();
if (compare && !hospitalType) hospitalType = 'Acute Care Hospitals';
if (!compare && !state && !city && !name) {
return { success: false, error: 'Provide at least one of: name, state, city (or set compare=true with a state).' };
}
if (compare && !state && !city && !hospitalType) {
// guard against a full-dataset scan with no filter
hospitalType = 'Acute Care Hospitals';
}
const conditions: any[] = [];
if (state) conditions.push({ property: 'state', value: state, operator: '=' });
if (city) conditions.push({ property: 'citytown', value: `%${city}%`, operator: 'like' });
if (name) conditions.push({ property: 'facility_name', value: `%${name}%`, operator: 'like' });
if (hospitalType) conditions.push({ property: 'hospital_type', value: `%${hospitalType}%`, operator: 'like' });
// Ownership: only push a SQL condition in list mode. In compare mode we always
// bucket in JS so every category shows up.
if (!compare && ownRaw) {
const pat = ownRaw.includes('for-profit') || ownRaw === 'forprofit' || ownRaw === 'proprietary'
? 'proprietary'
: (ownRaw.includes('non') && ownRaw.includes('profit')) || ownRaw === 'nonprofit'
? 'non-profit'
: ownRaw.includes('gov')
? 'government'
: ownRaw;
conditions.push({ property: 'hospital_ownership', value: `%${pat}%`, operator: 'like' });
}
let fetched;
try {
fetched = await fetchRows(conditions);
} catch (err: any) {
return { success: false, error: `CMS request failed: ${err.message}` };
}
let { rows } = fetched;
if (!rows.length) {
return { success: false, error: 'No matching hospitals in CMS Hospital General Information.' };
}
const scope = [
hospitalType || 'all types',
state || city || 'nationwide',
].join(', ');
if (compare) {
// In compare mode `ownership` (if given) just restricts which bucket(s) to show.
const wantBucket = ownRaw
? (ownRaw.includes('non') && ownRaw.includes('profit')) ? 'Non-profit'
: ownRaw.includes('profit') || ownRaw.includes('proprietary') ? 'For-profit'
: ownRaw.includes('gov') || ownRaw.includes('federal') ? 'Government'
: null
: null;
const groups = new Map<string, Row[]>();
for (const r of rows) {
const b = ownershipBucket(r.hospital_ownership);
if (wantBucket && b !== wantBucket) continue;
if (!groups.has(b)) groups.set(b, []);
groups.get(b)!.push(r);
}
const order = ['For-profit', 'Non-profit', 'Government', 'Other'];
const lines: string[] = [
`CMS hospital performance by ownership — ${scope}`,
fetched.truncated ? `(sampled ${rows.length} of ${fetched.total} matching rows)` : `(${rows.length} hospitals)`,
'',
'Ownership │ N │ rated │ avg★ │ rating 1/2/3/4/5 │ mortality ± │ safety ± │ readmission ±',
'──────────────┼──────┼───────┼──────┼─────────────────────┼───────────────┼──────────────┼──────────────',
];
const data: any[] = [];
const pm = (b: number, w: number) => `+${String(b).padStart(4)} / -${String(w).padStart(4)}`;
for (const key of order) {
const g = groups.get(key);
if (!g || !g.length) continue;
const s = summarize(g);
const d = s.rating_dist;
lines.push(
`${key.padEnd(13)} │ ${String(s.n).padStart(4)} │ ${String(s.rated).padStart(5)} │ ` +
`${(s.avg_rating ?? '—').toString().padStart(4)} │ ` +
`${`${d['1']}/${d['2']}/${d['3']}/${d['4']}/${d['5']}`.padEnd(19)} │ ` +
`${pm(s.mort_better, s.mort_worse)} │ ${pm(s.safety_better, s.safety_worse)} │ ${pm(s.readm_better, s.readm_worse)}`,
);
data.push({ ownership: key, ...s });
}
lines.push('');
lines.push('★ = CMS overall star rating (1–5, higher is better). "mortality/safety/readmission ±" =');
lines.push('total measure-outcomes across the group scored better (+) / worse (−) than the US national rate.');
lines.push('Source: CMS Provider Data Catalog, "Hospital General Information" (data.cms.gov).');
return { success: true, stdout: lines.join('\n'), data: { scope, truncated: fetched.truncated, total: fetched.total, groups: data } };
}
// list mode
const limit = Math.min(Math.max(1, Number(args?.max_results ?? 20)), 60);
rows = rows.slice(0, limit);
const lines: string[] = [`CMS hospitals — ${scope} (${fetched.total} matched, showing ${rows.length})\n`];
const data: any[] = [];
for (const r of rows) {
const rating = num(r.hospital_overall_rating);
lines.push(`• ${r.facility_name} — ${r.citytown}, ${r.state}`);
lines.push(` ${r.hospital_ownership} | ${r.hospital_type}${r.emergency_services === 'Yes' ? ' | ER' : ''}`);
lines.push(
` Overall rating: ${rating ?? 'not rated'}` +
` | mortality +${num(r.count_of_mort_measures_better) || 0}/-${num(r.count_of_mort_measures_worse) || 0}` +
` safety +${num(r.count_of_safety_measures_better) || 0}/-${num(r.count_of_safety_measures_worse) || 0}` +
` readmission +${num(r.count_of_readm_measures_better) || 0}/-${num(r.count_of_readm_measures_worse) || 0}`,
);
lines.push('');
data.push({
name: r.facility_name, city: r.citytown, state: r.state,
ownership: r.hospital_ownership, ownership_bucket: ownershipBucket(r.hospital_ownership),
type: r.hospital_type, overall_rating: rating,
mort_better: num(r.count_of_mort_measures_better), mort_worse: num(r.count_of_mort_measures_worse),
safety_better: num(r.count_of_safety_measures_better), safety_worse: num(r.count_of_safety_measures_worse),
readm_better: num(r.count_of_readm_measures_better), readm_worse: num(r.count_of_readm_measures_worse),
});
}
lines.push('Source: CMS Provider Data Catalog, "Hospital General Information" (data.cms.gov).');
return { success: true, stdout: lines.join('\n'), data: { scope, total: fetched.total, hospitals: data } };
},
};
+2
View File
@@ -28,6 +28,7 @@ import { emailListTool, emailReadTool, emailSendTool, emailSearchTool, emailDele
import { kakaoSendTool } from './kakao.js';
import { koreanLawSearchTool, koreanLawFetchTool, usCaseSearchTool } from './legal.js';
import { excelReadTool, excelWriteTool } from './excel.js';
import { cmsHospitalCompareTool } from './cms.js';
export interface Tool {
name: string;
@@ -199,6 +200,7 @@ class ToolRegistry {
// OpenAlex / Semantic Scholar tools
this.registerSafe(openalexSearchTool);
this.registerSafe(semanticSearchTool);
this.registerSafe(cmsHospitalCompareTool);
// Document & data tools
this.registerSafe(pdfReadTool);
this.registerSafe(pdfExtractImagesTool);